How can you pipe a readable stream to another readable stream?

时间:2015-09-11 15:15:06

标签: javascript node.js

I am doing exercises from the "stream-adventure", and I'm very uncertain about the stream-combiner module.

Specifically it says that:

The stream-combiner module creates a pipeline from a list of streams, returning a single stream that exposes the first stream as the writable side and the last stream as the readable side like the duplexer module, but with an arbitrary number of streams in between. Unlike the duplexer module, each stream is piped to the next. For example:

var combine = require('stream-combiner');
var stream = combine(a, b, c, d);

will internally do a.pipe(b).pipe(c).pipe(d) but the stream returned by combine() has its writable side hooked into a and its readable side hooked into d.

Now as it says, "its writable side hooked into a and its readable side hooked into d", one can use the above stream like follows:

someReadableStream.pipe(stream).pipe(someWritableStream)

But won't the above just become:

someReadableStream.pipe(a).pipe(b).pipe(c).pipe(d).pipe(someWritableStream)

My question is how can a readable stream pipe to another readable stream. And at the end, how can the result of piping to a writable stream again pipe to a writable stream.

2 个答案:

答案 0 :(得分:1)

这是一个文本示例,希望澄清有关流的规则,以便流组合器做一些有用的事情:

var rw = combine(r_or_rw, rw1, rw2, rw3, ...rwN, w_or_rw)

因此第一个流至少需要可读,内部流都需要读/写,最终流至少需要可写。返回的新流是可读/写的。当您写入返回的流时,它会通过管道向下发送新数据,当您读取时会从管道末端向您提供数据。

答案 1 :(得分:0)

你是正确的,它与readable.pipe(a).pipe(b).pipe(c).pipe(d).pipe(writable)相同, 组合器的优点是您无法从函数返回a.pipe(b).pipe(c).pipe(d),因此您必须始终手动连接它们。使用组合器,您可以从其他流中创建流,然后将其整理成功能或模块。

为了使其工作,但是,a,b,c,d都必须是变换流,它们都是可读写的。

相关问题