Skip to content
Myr

streaming.js

This file

Path

lib/pipe/streaming.js

51 lines · 2.4 KiB · JavaScript

Last changed by

Not known.

History of this file

Take it

The walk stopped after 200 commits: lines older than c8a6ed7 point at it.

Improve documentation (#1003)ehmickybefore adoptionc8a6ed7

lines 1–51why, one step back
1import {finished} from 'node:stream/promises';
2import mergeStreams from '@sindresorhus/merge-streams';3import {incrementMaxListeners} from '../utils/max-listeners.js';4import {pipeStreams} from '../io/pipeline.js';56// The piping behavior is like Bash.7// In particular, when one subprocess exits, the other is not terminated by a signal.8// Instead, its stdout (for the source) or stdin (for the destination) closes.9// If the subprocess uses it, it will make it error with SIGPIPE or EPIPE (for the source) or end (for the destination).10// If it does not use it, it will continue running.11// This allows for subprocesses to gracefully exit and lower the coupling between subprocesses.12export const pipeSubprocessStream = (sourceStream, destinationStream, maxListenersController) => {13 const mergedStream = MERGED_STREAMS.has(destinationStream)14 ? pipeMoreSubprocessStream(sourceStream, destinationStream)15 : pipeFirstSubprocessStream(sourceStream, destinationStream);16 incrementMaxListeners(sourceStream, SOURCE_LISTENERS_PER_PIPE, maxListenersController.signal);17 incrementMaxListeners(destinationStream, DESTINATION_LISTENERS_PER_PIPE, maxListenersController.signal);18 cleanupMergedStreamsMap(destinationStream);19 return mergedStream;20};2122// We use `merge-streams` to allow for multiple sources to pipe to the same destination.23const pipeFirstSubprocessStream = (sourceStream, destinationStream) => {24 const mergedStream = mergeStreams([sourceStream]);25 pipeStreams(mergedStream, destinationStream);26 MERGED_STREAMS.set(destinationStream, mergedStream);27 return mergedStream;28};2930const pipeMoreSubprocessStream = (sourceStream, destinationStream) => {31 const mergedStream = MERGED_STREAMS.get(destinationStream);32 mergedStream.add(sourceStream);33 return mergedStream;34};3536const cleanupMergedStreamsMap = async destinationStream => {37 try {38 await finished(destinationStream, {cleanup: true, readable: false, writable: true});39 } catch {}4041 MERGED_STREAMS.delete(destinationStream);42};4344const MERGED_STREAMS = new WeakMap();4546// Number of listeners set up on `sourceStream` by each `sourceStream.pipe(destinationStream)`47// Those are added by `merge-streams`48const SOURCE_LISTENERS_PER_PIPE = 2;49// Number of listeners set up on `destinationStream` by each `sourceStream.pipe(destinationStream)`50// Those are added by `finished()` in `cleanupMergedStreamsMap()`51const DESTINATION_LISTENERS_PER_PIPE = 1;