- Mastering Node.js(Second Edition)
- Sandro Pasquali Kevin Faaborg
- 178字
- 2021-07-02 19:28:49
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.
- MERN Quick Start Guide
- 物聯網檢驗檢測技術
- 萬物互聯:蜂窩物聯網組網技術詳解
- Windows Server 2003 Active Directory Design and Implementation: Creating, Migrating, and Merging Networks
- 面向云平臺的物聯網多源異構信息融合方法
- 電力物聯網工程技術原理與應用
- IPv6網絡切片:使能千行百業新體驗
- CCNP TSHOOT(642-832)認證考試指南
- 邁向自智網絡時代:IP自動駕駛網絡
- 4G小基站系統原理、組網及應用
- 網絡利他行為研究:積極心理學的視角
- Microsoft Power Platform Enterprise Architecture
- 互聯網安全的40個智慧洞見(2016)
- 圖神經網絡前沿
- 小型局域網組建