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

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.

主站蜘蛛池模板: 东光县| 金华市| 平武县| 珲春市| 清苑县| 牙克石市| 清徐县| 张家港市| 芜湖市| 漠河县| 大英县| 娱乐| 巨野县| 长岛县| 新郑市| 枣阳市| 长岭县| 乌兰察布市| 巴青县| 新兴县| 鹤壁市| 淮滨县| 宜都市| 广州市| 阳谷县| 阜南县| 灵璧县| 收藏| 勃利县| 花莲县| 肃宁县| 彭山县| 马山县| 东乌珠穆沁旗| 元氏县| 普格县| 梁山县| 辽宁省| 金堂县| 石台县| 若羌县|