![](/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.