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

故事扮演 提交于 2019-12-30 07:10:31

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!