Node.js: Capture STDOUT of `child_process.spawn`

前端 未结 3 900
-上瘾入骨i
-上瘾入骨i 2021-01-05 05:24

I need to capture in a custom stream outputs of a spawned child process.

child_process.spawn(command[, args][, options])

F

3条回答
  •  伪装坚强ぢ
    2021-01-05 06:07

    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 ...
    });
    

提交回复
热议问题