0

Say I have a named pipe on linux:

mkfifo lk.log

From the command line, I can do this to print out anything written to the name pipe file.

node monitor.js < lk.log

and pretend this is what the script looks like

// monitor.js

process.stdin.resume();
process.stdin.setEncoding('utf8');

// read data from stdin
process.stdin.on('data', function(chunk) {
    console.log(chunk);
});

How could I do this within node using child_process.spawn?

child_process.spawn('node', ['monitor.js'])...
Blake Regalia
  • 2,677
  • 2
  • 20
  • 29

3 Answers3

1

The easiest way would be to use exec():

var exec = require('child_process').exec;

exec('node monitor.js < lk.log', function(err, stdout, stderr) {
  ...
});

A more elaborate way would be to open the named pipe in node and pass it as stdin to the process you're spawning (see the option stdio for spawn).

robertklep
  • 198,204
  • 35
  • 394
  • 381
  • `child_process.exec` does not help me because it waits for the child process to terminate before being able to read from child's stdout. – Blake Regalia Mar 25 '13 at 21:23
  • Oops, you are correct. I guess checking out the stdio option for spawn is your only option. – robertklep Mar 25 '13 at 21:25
1

The answer is to use fs.open and the stdio options in child_process.spawn as such:

var spawn = require('child_process').spawn;

var fd_stdin = fs.openSync('lk.log', 'r');
spawn('node', ['monitor.js'], {
    stdio: [fd_stdin, 1, 2];
});
Blake Regalia
  • 2,677
  • 2
  • 20
  • 29
0

From Ben Noordhuis (Core Node contributor) - 10/11/11

Windows has a concept of named pipes but since you mention mkfifo I assume you mean UNIX FIFOs.

We don't support them and probably never will (FIFOs in non-blocking mode have the potential to deadlock the event loop) but you can use UNIX sockets if you need similar functionality.

https://groups.google.com/d/msg/nodejs/9TvDwCWaB5c/udQPigFvmgAJ

For unix sockets, see: https://stackoverflow.com/a/18226566/977939

Community
  • 1
  • 1
jpillora
  • 5,194
  • 2
  • 44
  • 56