2017-06-09 13 views
0

我目前正在使用模块through2,concat-streamrequest在Node.js中使用流实践。动态扩展Node.js中的管道链条

我设置了管链是这样的:

request(process.argv[2]) 
.pipe(through(write, end)) 
.pipe(/*And */) 
.pipe(/* Some */) 
.pipe(/* more */) 
.on("finish",function(){ #Do some stuff }); 

function write(buf, enc, nxt){ 
    /*Push some data after some processing*/ 
} 
function end(done){ 
    done() 
} 

这是管的静止链。是否可以通过某种形式的用户输入动态指定管道链?

在伪代码:

array_of_user_pipes = from_some_input; 
pipe_library = {pipe_name:pipe_callback} object, loaded into application logic 

perform the url request (fetch .txt file over the internet) 
for all pipe in array_of_user_pipes do 
    fetch pipe from pipe_library (simple key look-up) 
    chain pipe to chain 
execute the (dynamic) pipe chain 
+0

它看起来完全可行的做同样的。您是否遇到过实施此方法的任何具体问题? –

+0

只是不确定如何设置它,因为静态链是通过“方法链”来设置的,如果您正在迭代,这是不可能的,或者有另一种方法来添加管道到链? –

回答

1

在把你的伪代码没有问题的js

const pipesMap = { 
    pipeName1: require('pipe-module'), 
    pipeName2: function(){}, 
    ... 
} 

定义piper功能,通过每个需要管道名称,并返回一个函数,管道初始事件流其中。

const piper = pipes => request => 
     pipes.reduce((piped, pipe) => piped.pipe(pipesMap[pipe]), request) 


const userInputPipesArray = ['pipeName1', 'pipeName2'] 

piper(userInputPipesArray)(request(process.argv[2])).on('finish') 

编辑

你可以使用环

let piped = request(process.argv[2]) 

for(let pipe of userInputPipesArray) { 
    piped = piped.pipe(pipeMap[pipe]) 
} 

piped.on('finish', ...) 
+0

非常感谢,我会尝试一下。这种方法有一个特定的名称吗?我想阅读它。 –

+0

以这种方式使用'reduce'又名'fold'时,不确定是否有任何特殊名称。这可以通过使用for-loop来减少。 –

+0

谢谢。这看起来和我想要的完全一样,也许我太悲观了:) –