如何使用 node.js 查看 phantomjs 子进程的标准输出?

How to see stdout of a phantomjs child process using node.js?

在下面的 node.js 代码中,我通常必须等待 phantomjs 子进程终止才能获取标准输出。我想知道在 phantomjs 子进程为 运行 时是否有任何方法可以查看标准输出?

var path = require('path')
var childProcess = require('child_process')
var phantomjs = require('phantomjs')
var binPath = phantomjs.path

var childArgs = [
  path.join(__dirname, 'phantomjs-script.js'),
]

childProcess.execFile(binPath, childArgs, function(err, stdout, stderr) {
  // handle results 
})

您可以 spawn PhantomJS 作为子进程并订阅其 stdout 和 stderr 流以实时获取数据(而 exec 仅 returns 在程序执行后缓冲结果)。

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

var childArgs = [
  path.join(__dirname, 'phantomjs-script.js'),
];
var child = spawn(phantomjs.path, childArgs);

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

child.stderr.on('data', function (data) {
  console.log('stderr: ' + data);
});

child.on('close', function (code) {
  console.log('child process exited with code ' + code);
});