stream.js
This file
Path
lib/stream.js
179 lines · 7.6 KiB · JavaScript
Last changed by
Improve `killSignal` option (#728)ehmickybefore adoptioncf36c1d
History of this fileTake it
The walk stopped after 200 commits: lines older than df08cfb point at it.
Allow `stdin` to be a sync/async iterable (#604)ehmickybefore adoptionec380db
line 1why, one step back1import {once} from 'node:events';Support file path and URL types in the `stdout` and `stderr` options (#621)ehmickybefore adoptionb369efe
line 2why, one step back2import {finished} from 'node:stream/promises';Allow any type with transforms (#709)ehmickybefore adoptioned8b2ce
line 3why, one step back3import getStream, {getStreamAsArrayBuffer, getStreamAsArray} from 'get-stream';Require Node.js 18Sindre Sorhusbefore adoption834e372
line 4why, one step back4import mergeStreams from '@sindresorhus/merge-streams';Use `async/await` instead of direct `Promise` manipulation (#659)ehmickybefore adoption7122767
line 5why, one step back5import {throwOnTimeout, cleanupOnExit} from './kill.js';Fix Node.js streams not being cleaned up on process error (#660)ehmickybefore adoption61a1623
line 6why, one step back6import {STANDARD_STREAMS} from './stdio/native.js';Allow any type with transforms (#709)ehmickybefore adoptioned8b2ce
line 7why, one step back7import {generatorToDuplexStream} from './stdio/generator.js';Upgrade dependencies (#396)ehmickybefore adoptiondf08cfb
lines 8–9why, one step back89// `all` interleaves `stdout` and `stderr`Fix `all` option combined with `ignore` (#703)ehmickybefore adoption7707fc7
lines 10–12why, one step back10export const makeAllStream = ({stdout, stderr}, {all}) => all && (stdout || stderr)11 ? mergeStreams([stdout, stderr].filter(Boolean))12 : undefined;Upgrade dependencies (#396)ehmickybefore adoptiondf08cfb
lines 13–14why, one step back1314// On failure, `result.stdout|stderr|all` should contain the currently buffered streamImprove error handling (#647)ehmickybefore adoption5b6d859
lines 15–16why, one step back15// They are automatically closed and flushed by Node.js when the child process exits16// We guarantee this by calling `childProcess.kill()`Fix `error.stdout|stderr|all` type when `encoding` option is used (#652)ehmickybefore adoptioncff6847
lines 17–18why, one step back17// When `buffer` is `false`, `streamPromise` is `undefined` and there is no buffered data to retrieve18const getBufferedData = async (streamPromise, encoding) => {Upgrade dependencies (#396)ehmickybefore adoptiondf08cfb
lines 19–21why, one step back19 try {20 return await streamPromise;21 } catch (error) {Allow any type with transforms (#709)ehmickybefore adoptioned8b2ce
lines 22–24why, one step back22 return error.bufferedData === undefined || Array.isArray(error.bufferedData)23 ? error.bufferedData24 : applyEncoding(error.bufferedData, encoding);Upgrade dependencies (#396)ehmickybefore adoptiondf08cfb
lines 25–27why, one step back25 }26};27Allow any type with transforms (#709)ehmickybefore adoptioned8b2ce
line 28why, one step back28const getStdioPromise = ({stream, stdioStreams, encoding, buffer, maxBuffer}) => stdioStreams[0].direction === 'output'Upgrade `merge-streams` (#717)ehmickybefore adoption8ef8e90
line 29why, one step back29 ? getStreamPromise({stream, encoding, buffer, maxBuffer})Simplify `std*` options logic (#691)ehmickybefore adoption98b0ee3
line 30why, one step back30 : undefined;Add `result.stdio` and `error.stdio` (#676)ehmickybefore adoption62a5207
line 31why, one step back31Upgrade `merge-streams` (#717)ehmickybefore adoption8ef8e90
line 32why, one step back32const getAllPromise = ({spawned, encoding, buffer, maxBuffer}) => getStreamPromise({stream: getAllStream(spawned, encoding), encoding, buffer, maxBuffer: maxBuffer * 2});Allow any type with transforms (#709)ehmickybefore adoptioned8b2ce
lines 33–50why, one step back3334// When `childProcess.stdout` is in objectMode but not `childProcess.stderr` (or the opposite), we need to use both:35// - `getStreamAsArray()` for the chunks in objectMode, to return as an array without changing each chunk36// - `getStreamAsArrayBuffer()` or `getStream()` for the chunks not in objectMode, to convert them from Buffers to string or Uint8Array37// We do this by emulating the Buffer -> string|Uint8Array conversion performed by `get-stream` with our own, which is identical.38const getAllStream = ({all, stdout, stderr}, encoding) => all && stdout && stderr && stdout.readableObjectMode !== stderr.readableObjectMode39 ? all.pipe(generatorToDuplexStream({value: allStreamGenerator, encoding}).value)40 : all;4142const allStreamGenerator = {43 async * transform(chunks) {44 yield * chunks;45 },46 binary: true,47 writableObjectMode: true,48 readableObjectMode: true,49};50Upgrade `merge-streams` (#717)ehmickybefore adoption8ef8e90
line 51why, one step back51const getStreamPromise = async ({stream, encoding, buffer, maxBuffer}) => {Upgrade dependencies (#396)ehmickybefore adoptiondf08cfb
lines 52–55why, one step back52 if (!stream || !buffer) {53 return;54 }55Upgrade `merge-streams` (#717)ehmickybefore adoption8ef8e90
line 56why, one step back56 if (stream.readableObjectMode) {Allow any type with transforms (#709)ehmickybefore adoptioned8b2ce
lines 57–59why, one step back57 return getStreamAsArray(stream, {maxBuffer});58 }59Fix `encoding` option (#696)ehmickybefore adoptionb6f9fa2
lines 60–62why, one step back60 const contents = encoding === 'buffer'61 ? await getStreamAsArrayBuffer(stream, {maxBuffer})62 : await getStream(stream, {maxBuffer});Fix `error.stdout|stderr|all` type when `encoding` option is used (#652)ehmickybefore adoptioncff6847
lines 63–65why, one step back63 return applyEncoding(contents, encoding);64};65Fix `encoding` option (#696)ehmickybefore adoptionb6f9fa2
line 66why, one step back66const applyEncoding = (contents, encoding) => encoding === 'buffer' ? new Uint8Array(contents) : contents;Upgrade dependencies (#396)ehmickybefore adoptiondf08cfb
line 67why, one step back67Use `async/await` instead of direct `Promise` manipulation (#659)ehmickybefore adoption7122767
line 68why, one step back68// Retrieve streams created by the `std*` optionsSimplify `std*` options logic (#691)ehmickybefore adoption98b0ee3
line 69why, one step back69const getCustomStreams = stdioStreamsGroups => stdioStreamsGroups.flat().filter(({type}) => type !== 'native');Use `async/await` instead of direct `Promise` manipulation (#659)ehmickybefore adoption7122767
line 70why, one step back70Wait for `WritableStream` completion (#645)ehmickybefore adoptionfb73bd1
lines 71–77why, one step back71// Some `stdout`/`stderr` options create a stream, e.g. when passing a file path.72// The `.pipe()` method automatically ends that stream when `childProcess.stdout|stderr` ends.73// This makes sure we want for the completion of those streams, in order to catch any error.74// Since we want to end those streams, they cannot be infinite, except for `process.stdout|stderr`.75// However, for the `stdin`/`input`/`inputFile` options, we only wait for errors, not completion.76// This is because source streams completion should end destination streams, but not the other way around.77// This allows for source streams to pipe to multiple destinations.Improve syntax of `std*: filePath` option (#671)ehmickybefore adoption90e0e13
line 78why, one step back78// We make an exception for `fileUrl` and `filePath`, since we create that source stream and we know it is piped to a single destination.Use `async/await` instead of direct `Promise` manipulation (#659)ehmickybefore adoption7122767
lines 79–81why, one step back79const waitForCustomStreamsEnd = customStreams => customStreams80 .filter(({value, type, direction}) => shouldWaitForCustomStream(value, type, direction))81 .map(({value}) => finished(value));Allow `stdin` to be a sync/async iterable (#604)ehmickybefore adoptionec380db
line 82why, one step back82Use `async/await` instead of direct `Promise` manipulation (#659)ehmickybefore adoption7122767
lines 83–85why, one step back83const throwOnCustomStreamsError = customStreams => customStreams84 .filter(({value, type, direction}) => !shouldWaitForCustomStream(value, type, direction))85 .map(({value}) => throwOnStreamError(value));Support file path and URL types in the `stdout` and `stderr` options (#621)ehmickybefore adoptionb369efe
line 86why, one step back86Improve syntax of `std*: filePath` option (#671)ehmickybefore adoption90e0e13
lines 87–88why, one step back87const shouldWaitForCustomStream = (value, type, direction) => (type === 'fileUrl' || type === 'filePath')88 || (direction === 'output' && !STANDARD_STREAMS.includes(value));Refactor execa promise to use `async/await` (#653)ehmickybefore adoptiond69fd23
line 89why, one step back89Use `async/await` instead of direct `Promise` manipulation (#659)ehmickybefore adoption7122767
lines 90–91why, one step back90const throwIfStreamError = stream => stream === null ? [] : [throwOnStreamError(stream)];91Allow `stdin` to be a sync/async iterable (#604)ehmickybefore adoptionec380db
lines 92–96why, one step back92const throwOnStreamError = async stream => {93 const [error] = await once(stream, 'error');94 throw error;95};96Improve error handling (#647)ehmickybefore adoption5b6d859
lines 97–99why, one step back97// The streams created by the `std*` options are automatically ended by `.pipe()`.98// However `.pipe()` only does so when the source stream ended, not when it errored.99// Therefore, when `childProcess.stdin|stdout|stderr` errors, those streams must be manually destroyed.Use `async/await` instead of direct `Promise` manipulation (#659)ehmickybefore adoption7122767
line 100why, one step back100const cleanupStdioStreams = (customStreams, error) => {Simplify `std*` options logic (#691)ehmickybefore adoption98b0ee3
lines 101–103why, one step back101 for (const {value} of customStreams) {102 if (!STANDARD_STREAMS.includes(value)) {103 value.destroy(error);Allow `stdin`/`stdout`/`stderr` to be an array (#643)ehmickybefore adoption7efd50c
lines 104–107why, one step back104 }105 }106};107Improve process termination (#724)ehmickybefore adoption1c48d37
lines 108–130why, one step back108// Like `once()` except it never rejects, especially not on `error` event.109const pEvent = (eventEmitter, eventName) => new Promise(resolve => {110 eventEmitter.once(eventName, (...payload) => {111 resolve([eventName, ...payload]);112 });113});114115const throwOnProcessError = async processErrorPromise => {116 const [, error] = await processErrorPromise;117 throw error;118};119120// First the `spawn` event is emitted, then `exit`.121// If the `error` event is emitted:122// - before `spawn`: `exit` is never emitted.123// - after `spawn`: `exit` is always emitted.124// We only want to listen to `exit` if it will be emitted, i.e. if `spawn` has been emitted.125// Therefore, the arguments order of `Promise.race()` is significant.126const waitForFailedProcess = async (processSpawnPromise, processErrorPromise, processExitPromise) => {127 const [eventName] = await Promise.race([processSpawnPromise, processErrorPromise]);128 return eventName === 'spawn' ? processExitPromise : [];129};130Upgrade dependencies (#396)ehmickybefore adoptiondf08cfb
line 131why, one step back131// Retrieve result of child process: exit code, signal, error, streams (stdout/stderr/all)Improve graceful exit (#714)ehmickybefore adoption5eeaab5
line 132why, one step back132export const getSpawnedResult = async ({Support file path and URL types in the `stdout` and `stderr` options (#621)ehmickybefore adoptionb369efe
line 133why, one step back133 spawned,Improve `killSignal` option (#728)ehmickybefore adoptioncf36c1d
line 134why, one step back134 options: {encoding, buffer, maxBuffer, timeoutDuration: timeout, cleanup, detached},Use `async/await` instead of direct `Promise` manipulation (#659)ehmickybefore adoption7122767
line 135why, one step back135 context,Simplify `std*` options logic (#691)ehmickybefore adoption98b0ee3
line 136why, one step back136 stdioStreamsGroups,Improve graceful exit (#714)ehmickybefore adoption5eeaab5
lines 137–138why, one step back137 controller,138}) => {Improve process termination (#724)ehmickybefore adoption1c48d37
lines 139–142why, one step back139 const processSpawnPromise = pEvent(spawned, 'spawn');140 const processErrorPromise = pEvent(spawned, 'error');141 const processExitPromise = pEvent(spawned, 'exit');142Improve graceful exit (#714)ehmickybefore adoption5eeaab5
line 143why, one step back143 const removeExitHandler = cleanupOnExit(spawned, cleanup, detached);Simplify `std*` options logic (#691)ehmickybefore adoption98b0ee3
line 144why, one step back144 const customStreams = getCustomStreams(stdioStreamsGroups);Use `async/await` instead of direct `Promise` manipulation (#659)ehmickybefore adoption7122767
line 145why, one step back145Allow any type with transforms (#709)ehmickybefore adoptioned8b2ce
line 146why, one step back146 const stdioPromises = spawned.stdio.map((stream, index) => getStdioPromise({stream, stdioStreams: stdioStreamsGroups[index], encoding, buffer, maxBuffer}));Upgrade `merge-streams` (#717)ehmickybefore adoption8ef8e90
line 147why, one step back147 const allPromise = getAllPromise({spawned, encoding, buffer, maxBuffer});Wait for streams completion on errors (#722)ehmickybefore adoption195369f
line 148why, one step back148 const customStreamsEndPromises = waitForCustomStreamsEnd(customStreams);Upgrade dependencies (#396)ehmickybefore adoptiondf08cfb
lines 149–150why, one step back149150 try {Use `async/await` instead of direct `Promise` manipulation (#659)ehmickybefore adoption7122767
lines 151–152why, one step back151 return await Promise.race([152 Promise.all([Improve process termination (#724)ehmickybefore adoption1c48d37
lines 153–154why, one step back153 undefined,154 processExitPromise,Add `result.stdio` and `error.stdio` (#676)ehmickybefore adoption62a5207
line 155why, one step back155 Promise.all(stdioPromises),Use `async/await` instead of direct `Promise` manipulation (#659)ehmickybefore adoption7122767
line 156why, one step back156 allPromise,Wait for streams completion on errors (#722)ehmickybefore adoption195369f
line 157why, one step back157 ...customStreamsEndPromises,Use `async/await` instead of direct `Promise` manipulation (#659)ehmickybefore adoption7122767
line 158why, one step back158 ]),Improve process termination (#724)ehmickybefore adoption1c48d37
line 159why, one step back159 throwOnProcessError(processErrorPromise),Use `async/await` instead of direct `Promise` manipulation (#659)ehmickybefore adoption7122767
lines 160–161why, one step back160 ...throwOnCustomStreamsError(customStreams),161 ...throwIfStreamError(spawned.stdin),Improve `killSignal` option (#728)ehmickybefore adoptioncf36c1d
line 162why, one step back162 ...throwOnTimeout(timeout, context, controller),Support file path and URL types in the `stdout` and `stderr` options (#621)ehmickybefore adoptionb369efe
line 163why, one step back163 ]);Upgrade dependencies (#396)ehmickybefore adoptiondf08cfb
line 164why, one step back164 } catch (error) {Improve error handling (#647)ehmickybefore adoption5b6d859
lines 165–166why, one step back165 spawned.kill();166 const results = await Promise.all([Improve process termination (#724)ehmickybefore adoption1c48d37
lines 167–168why, one step back167 error,168 waitForFailedProcess(processSpawnPromise, processErrorPromise, processExitPromise),Add `result.stdio` and `error.stdio` (#676)ehmickybefore adoption62a5207
line 169why, one step back169 Promise.all(stdioPromises.map(stdioPromise => getBufferedData(stdioPromise, encoding))),Fix `error.stdout|stderr|all` type when `encoding` option is used (#652)ehmickybefore adoptioncff6847
line 170why, one step back170 getBufferedData(allPromise, encoding),Upgrade dependencies (#396)ehmickybefore adoptiondf08cfb
line 171why, one step back171 ]);Use `async/await` instead of direct `Promise` manipulation (#659)ehmickybefore adoption7122767
line 172why, one step back172 cleanupStdioStreams(customStreams, error);Wait for streams completion on errors (#722)ehmickybefore adoption195369f
line 173why, one step back173 await Promise.allSettled(customStreamsEndPromises);Improve error handling (#647)ehmickybefore adoption5b6d859
line 174why, one step back174 return results;Use `async/await` instead of direct `Promise` manipulation (#659)ehmickybefore adoption7122767
line 175why, one step back175 } finally {Improve graceful exit (#714)ehmickybefore adoption5eeaab5
lines 176–177why, one step back176 controller.abort();177 removeExitHandler?.();Upgrade dependencies (#396)ehmickybefore adoptiondf08cfb
lines 178–179why, one step back178 }179};