Skip to content
Myr

duplex.js

This file

Path

lib/stdio/duplex.js

43 lines · 1.9 KiB · JavaScript

Last changed by

Separate generator -> Duplex utility (#698)ehmickybefore adoption214b6ab

History of this file

Take it

Separate generator -> Duplex utility (#698)ehmickybefore adoption214b6ab

lines 1–43why, one step back
1import {Duplex, Readable, PassThrough, getDefaultHighWaterMark} from 'node:stream';
23/*4Transform an array of generator functions into a `Duplex`.56The `Duplex` is created by `Duplex.from()` made of a writable stream and a readable stream, piped to each other.7- The writable stream is a simple `PassThrough`, so it only forwards data to the readable part.8- The `PassThrough` is read as an iterable using `passThrough.iterator()`.9- This iterable is transformed to another iterable, by applying the encoding generators.10 Those convert the chunk type from `Buffer` to `string | Uint8Array` depending on the encoding option.11- This new iterable is transformed again to another one, this time by applying the user-supplied generator.12- Finally, `Readable.from()` is used to convert this final iterable to a `Readable` stream.13*/14export const generatorsToDuplex = (generators, {objectMode}) => {15 const highWaterMark = getDefaultHighWaterMark(objectMode);16 const passThrough = new PassThrough({objectMode, highWaterMark, destroy: destroyPassThrough});17 let iterable = passThrough.iterator();1819 for (const generator of generators) {20 iterable = generator(iterable);21 }2223 const readableStream = Readable.from(iterable, {objectMode, highWaterMark});24 const duplexStream = Duplex.from({writable: passThrough, readable: readableStream});25 return duplexStream;26};2728/*29When an error is thrown in a generator, the PassThrough is aborted.3031This creates a race condition for which error is propagated, due to the Duplex throwing twice:32- The writable side is aborted (PassThrough)33- The readable side propagate the generator's error3435In order for the later to win that race, we need to wait one microtask.36- However we wait one macrotask instead to be on the safe side37- See https://github.com/sindresorhus/execa/pull/693#discussion_r145380945038*/39const destroyPassThrough = (error, done) => {40 setTimeout(() => {41 done(error);42 }, 0);43};