首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在node.js中使用event-stream将可读的流传送到child_process.exec命令?

如何在node.js中使用event-stream将可读的流传送到child_process.exec命令?
EN

Stack Overflow用户
提问于 2013-02-27 15:16:26
回答 1查看 844关注 0票数 1

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

代码语言:javascript
复制
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命令和流式传输输出的原理是相同的。

EN

回答 1

Stack Overflow用户

发布于 2014-05-18 09:01:14

我不会使用event-stream,它是基于较旧的stream API的。

对于故障线路,我将使用through2

代码语言:javascript
复制
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.
    }
)

我还没有测试过这个,但这就是我处理这个问题的方法。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/15106236

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档