如何使用node.js查看phantomjs子进程的stdout

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

本文关键字:子进程 stdout phantomjs 查看 何使用 node js      更新时间:2023-09-26

在下面的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 
})

您可以将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);
});