2015-11-30 73 views
3

在下面的node.js代碼中,我通常必須等待phantomjs子進程終止以獲取stdout。我想知道在phantomjs子進程運行時是否有任何方法可以看到stdout?如何使用node.js查看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 
}) 

回答

5

可以spawn PhantomJS作爲一個子進程,並訂閱其輸出和錯誤流來獲得實時數據(而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); 
}); 
相關問題