逐行解析生成的node.js子进程的输出 [英] Parse output of spawned node.js child process line by line
问题描述
我有一个PhantomJS/CasperJS脚本,它是使用process.spawn()
从node.js脚本中运行的.由于CasperJS不支持require()
ing模块,因此我尝试将命令从CasperJS打印到stdout
,然后使用spawn.stdout.on('data', function(data) {});
从我的node.js脚本中读取它们,以进行将对象添加到redis的操作. /mongoose(令人费解,是的,但是比为此设置Web服务要简单得多.)CasperJS脚本执行一系列命令并创建例如20个屏幕快照,需要将其添加到我的数据库中.
I have a PhantomJS/CasperJS script which I'm running from within a node.js script using process.spawn()
. Since CasperJS doesn't support require()
ing modules, I'm trying to print commands from CasperJS to stdout
and then read them in from my node.js script using spawn.stdout.on('data', function(data) {});
in order to do things like add objects to redis/mongoose (convoluted, yes, but seems more straightforward than setting up a web service for this...) The CasperJS script executes a series of commands and creates, say, 20 screenshots which need to be added to my database.
但是,我不知道如何将data
变量(Buffer
?)分成几行...我尝试将其转换为字符串,然后进行替换,正在执行spawn.stdout.setEncoding('utf8');
,但似乎没有任何效果...
However, I can't figure out how to break the data
variable (a Buffer
?) into lines... I've tried converting it to a string and then doing a replace, I've tried doing spawn.stdout.setEncoding('utf8');
but nothing seems to work...
这就是我现在拥有的
var spawn = require('child_process').spawn;
var bin = "casperjs"
//googlelinks.js is the example given at http://casperjs.org/#quickstart
var args = ['scripts/googlelinks.js'];
var cspr = spawn(bin, args);
//cspr.stdout.setEncoding('utf8');
cspr.stdout.on('data', function (data) {
var buff = new Buffer(data);
console.log("foo: " + buff.toString('utf8'));
});
cspr.stderr.on('data', function (data) {
data += '';
console.log(data.replace("\n", "\nstderr: "));
});
cspr.on('exit', function (code) {
console.log('child process exited with code ' + code);
process.exit(code);
});
https://gist.github.com/2131204
推荐答案
尝试一下:
cspr.stdout.setEncoding('utf8');
cspr.stdout.on('data', function(data) {
var str = data.toString(), lines = str.split(/(\r?\n)/g);
for (var i=0; i<lines.length; i++) {
// Process the line, noting it might be incomplete.
}
});
请注意,数据"事件不一定在输出的两行之间平均中断,因此一行可能跨越多个数据事件.
Note that the "data" event might not necessarily break evenly between lines of output, so a single line might span multiple data events.
这篇关于逐行解析生成的node.js子进程的输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!