gpt4 book ai didi

node.js - 如何使用node.js中的事件流将可读流传输到child_process.exec命令?

转载 作者:太空宇宙 更新时间:2023-11-04 02:41:23 25 4
gpt4 key购买 nike

我有以下(不起作用)代码:

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()流写入的 block 。如何实现这一目标?另请注意,“ls”和“cat”不是我使用的实际命令,但执行动态生成的 unix 命令和流式输出的原理是相同的。

最佳答案

我不会使用 event-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.
}
)

我还没有对此进行测试,但这就是我解决问题的方法。

关于node.js - 如何使用node.js中的事件流将可读流传输到child_process.exec命令?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15106236/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com