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

前端 未结 3 901
-上瘾入骨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 05:54

    Hi I'm on my phone but I will try to guide you as I can. I will clarify when near a computer if needed

    What I think you want is to read the stdout from a spawn and do something with the data?

    You can give the spawn a variable name instead of just running the function, e.g:

    var child = spawn();
    

    Then listen to the output like:

    child.stdout.on('data', function(data) {
        console.log(data.toString());
    });
    

    You could use that to write the data then to a file or whatever you may want to do with it.

    0 讨论(0)
  • 2021-01-05 06:06

    You can do it without using a temporary file:

    var process = child_process.spawn(command[, args][, options]);
    process.stdout.on('data', function (chunk) {
        console.log(chunk);
    });
    
    0 讨论(0)
  • 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 ...
    });
    
    0 讨论(0)
提交回复
热议问题