Search code examples
node.jsnode.js-stream

Extra stdio streams for node.js process


The node.js API documents using an extra stdio (fd=4) when spawning a child process:

// Open an extra fd=4, to interact with programs present a
// startd-style interface.
spawn('prg', [], { stdio: ['pipe', null, null, null, 'pipe'] });

That stdio would be available to the parent process via ChildProcess.stdio[fd].

How can the child process access these extra stdios? Let's use a stream instead of a pipe on file descriptor 3 (fd=3).

/* parent process */

// open file for read/write
var mStream = fs.openSync('./shared-stream', 'r+');

// spawn child process with stream object as fd=3
spawn('node', ['/path/to/child.js'], {stdio: [0, 1, 2, mStream] });

Solution

  • Although node.js does not document this in the API, you can read/write to these streams with the index number of the file descriptor using fs.read and fs.write.

    I have not found anything from inspecting the process object that indicates the presence of these stdios available to the child process, so as far as I know, you would not be able to detect whether or not those stdios are available from the child.

    However, if you know for sure that your child process will be spawned with these stdios, then you can use read/write functions like so:

    var fd_index = 3;
    fs.write(fd_index, new Buffer(data, 'utf8'), 0, data.length, null, function(err, bytesWritten, buffer) {
       if(err) return failure();
       else ...
       // success
    });