本文介绍了如何使用node.js查看phantomjs子进程的标准输出?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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
})

推荐答案

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

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);
});

这篇关于如何使用node.js查看phantomjs子进程的标准输出?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-23 07:04