如何使用node.js查看phantomjs子进程的Stdout?[英] How to see stdout of a phantomjs child process using node.js?

问题描述

在以下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);
});

本文地址:https://www.itbaoku.cn/post/1739886.html