在块上获取 execFile stdOut

get execFile stdOut on chunks

我正在尝试使用 execFile 并记录给出任务完成百分比的 stdOut,但回调函数:

var child = require('child_process');

child.execFile("path/to/the/file", options, function (error, stdout, stderr) {
    console.log('stdout: ' + stdout);
});

等待过程完成,然后立即记录所有内容。 如何在处理过程中获取信息并将其分段记录?我试过这个:

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

但是我得到这个错误:Cannot read property 'on' of undefined"

您应该使用 .spawn() 而不是 .exec()/.execFile() 来流式传输输出:

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

var child = spawn("path/to/the/file", args);

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

child.on('close', function(code, signal) {
  // process exited and no more data available on `stdout`/`stderr`
});