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

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.

主站蜘蛛池模板: 北海市| 张北县| 长丰县| 韶关市| 改则县| 湾仔区| 青海省| 商都县| 玛曲县| 珲春市| 石台县| 濮阳市| 武隆县| 奉贤区| 宝鸡市| 凤山县| 登封市| 定襄县| 剑阁县| 佛学| 浦江县| 都江堰市| 靖西县| 深水埗区| 西峡县| 马龙县| 西乌| 尚义县| 陈巴尔虎旗| 文山县| 望都县| 孝义市| 桃园市| 贵州省| 宁津县| 宁安市| 富川| 庄河市| 越西县| 博湖县| 临高县|