在下面的node.js代码中,我通常必须等待phantomjs子进程终止以获取stdout。我想知道在phantomjs子进程运行时是否有任何方法可以看到stdout?
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
})
答案 0 :(得分:5)
您可以spawn
PhantomJS作为子进程并订阅其stdout和stderr流以实时获取数据(而exec
仅在程序执行后返回缓冲结果)。
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);
});