官术网_书友最值得收藏!

Using PassThrough streams

This sort of stream is a trivial implementation of a Transform stream, which simply passes received input bytes through to an output stream. This is useful if one doesn't require any transformation of the input data, and simply wants to easily pipe a Readable stream to a Writable stream.

PassThrough streams have benefits similar to JavaScript's anonymous functions, making it easy to assert minimal functionality without too much fuss. For example, it is not necessary to implement an abstract base class, as one does with for the _read method of a Readable stream. Consider the following use of a PassThrough stream as an event spy:

const fs = require('fs');
const stream = require('stream');
const spy = new stream.PassThrough();

spy
.on('error', (err) => console.error(err))
.on('data', function(chunk) {
console.log(`spied data -> ${chunk}`);
})
.on('end', () => console.log('\nfinished'));

fs.createReadStream('./passthrough.txt').pipe(spy).pipe(process.stdout);

Normally a Transform or Duplex stream is what you want (where you can set up a proper implementation of _read and _write), but in certain scenarios, such as tests, it can be useful to place "watchers" on a stream.

主站蜘蛛池模板: 江华| 隆德县| 台山市| 沿河| 宝坻区| 满洲里市| 正定县| 曲周县| 东乌珠穆沁旗| 济源市| 遂平县| 凤台县| 祁连县| 靖边县| 潮州市| 昌乐县| 义乌市| 开封县| 台湾省| 宁强县| 东宁县| 江川县| 西青区| 龙游县| 丹棱县| 绍兴市| 卓尼县| 长春市| 大田县| 九龙坡区| 宣武区| 天长市| 启东市| 虞城县| 万州区| 永城市| 云阳县| 大悟县| 新邵县| 宁乡县| 洱源县|