总结一下 pipe 的过程:
- 首先执行 readbable.pipe(writable),将 readable 与 writable 对接上
- 当 readable 中有数据时,readable.emit(‘data’),将数据写入 writable
- 如果 writable.write(chunk) 返回 false,则进入 pause 模式,等待 drain 事件触发
- drain 事件全部触发后,再次进入 flow 模式,写入数据
- 不管数据写入完成或发生中断,最后都会调用 unpipe()
- unpipe() 调用 Readable.prototype.unpipe(),触发 dest 的 unpipe 事件,清理相关数据
官网使用例子:
```javascript // 当在可读流上调用 stream.pipe() 方法将此可写流添加到其目标集时,则触发 ‘pipe’ 事件。
const writer = getWritableStreamSomehow(); const reader = getReadableStreamSomehow();
writer.on(‘pipe’, (src) => { console.log(‘Something is piping into the writer.’); assert.equal(src, reader); });
reader.pipe(writer); ```