2013-02-27 68 views
1

我有以下的(非工作)代碼:如何使用node.js中的事件流將可讀流管道化爲child_process.exec命令?

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))其中datamap()流寫入的塊英寸如何實現這一目標?同時請注意,「LS」和「貓」是不是我使用實際的命令,但執行動態生成的UNIX命令和流輸出的原理是一樣的。

+0

你不能。你必須使用'child_process.spawn' – 2013-09-26 08:53:30

回答

0

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

我還沒有測試,但是這是我將如何處理這個問題。

相關問題