【问题标题】:how to pipe readable stream to a child_process.exec command using event-stream in node.js?如何使用 node.js 中的事件流将可读流通过管道传输到 child_process.exec 命令?
【发布时间】:2013-02-27 07:16:25
【问题描述】:

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

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 命令和流式输出的原理是相同的。

【问题讨论】:

  • 你不能。你必须使用child_process.spawn

标签: node.js event-stream


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-06-04
    • 2023-03-24
    • 1970-01-01
    • 1970-01-01
    • 2016-09-17
    • 2021-03-03
    • 2015-07-23
    相关资源
    最近更新 更多