![](/img/trans.png)
[英]How to access command line arguments in a node.js child process using child_process.exec?
[英]how to pipe readable stream to a child_process.exec command using event-stream in node.js?
我有以下(无效)代码:
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命令并流输出的原理是相同的。
我不会使用基于旧流API的event-stream
。
对于故障线路,我将使用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.
}
)
我还没有测试,但这就是我要解决的问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.