I need to capture in a custom stream outputs of a spawned child process.
child_process.spawn(command[, args][, options])
F
The stdio
option requires file descriptors, not stream objects, so one way to do it is use use fs.openSync()
to create an output file descriptor and us that.
Taking your first example, but using fs.openSync()
:
var s = fs.openSync('/tmp/test.txt', 'w');
var p = child_process.spawn('ifconfig', [], {stdio: [process.stdin, s, process.stderr]});
You could also set both stdout and stderr to the same file descriptor (for the same effect as bash's 2>&1
).
You'll need to close the file when you are done, so:
p.on('close', function(code) {
fs.closeSync(s);
// do something useful with the exit code ...
});