问题
In the following node.js code, I normally have to wait for the phantomjs child process to terminate to get the stdout. I am wondering if there is any way to see the stdout while the phantomjs child process is running?
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
})
回答1:
You can spawn
PhantomJS as a child process and subscribe to its stdout and stderr streams to get data realtime (whereas exec
only returns buffered result after program execution).
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);
});
来源:https://stackoverflow.com/questions/33992091/how-to-see-stdout-of-a-phantomjs-child-process-using-node-js