我有以下(不起作用的)代码:
var es = require('event-stream');
var cp = require('child_process');
es.pipeline(
es.child(cp.exec("ls")),
es.split(/[\t\s]+/),
es.map(function(data,cb){
if ( /\.txt$/.test(data) ) cb(null, data);
else cb();
}),
es.child(cp.exec("cat "+data)) // this doesn't work
)问题出在最后一个流es.child(cp.exec("cat "+data))中,其中data是从map()流写入的块。如何才能做到这一点?还请注意,"ls“和"cat”不是我实际使用的命令,但执行动态生成的unix命令和流式传输输出的原理是相同的。
发布于 2014-05-18 09:01:14
我不会使用event-stream,它是基于较旧的stream API的。
对于故障线路,我将使用through2
var thr = require('through2').obj
var es = require('event-stream');
var cp = require('child_process');
function finalStream (cmd) {
return thr(function(data, enc, next){
var push = this.push
// note I'm not handling any error from the child_process here
cp.exec(cmd +' '+ data).stdout.pipe(thr(function(chunk, enc, next){
push(chunk)
next()
}))
.on('close', function(errorCode){
if (errorCode) throw new Error('ops')
next()
})
})
}
es.pipeline(
es.child(cp.exec("ls")),
es.split(/[\t\s]+/),
es.map(function(data,cb){
if ( /\.txt$/.test(data) ) cb(null, data);
else cb();
}),
finalStream('cat')
thr(function(chunk, enc, next){
// do stuff with the output of cat.
}
)我还没有测试过这个,但这就是我处理这个问题的方法。
https://stackoverflow.com/questions/15106236
复制相似问题