Add `.readableStream()`, `.writableStream()` and `.transformStream()` methods (#1254)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Sindre Sorhus · committed by GitHub · parent 522654a · Browse files · 14 files·+297 added−4 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
14 files+297 added−4 removed
- tests:+126 added−0 removed
- other:+171 added−4 removed
Provenance
- Commit
29d9cfc- Tree
84a751d- Author
Sindre Sorhus <sindresorhus@gmail.com>- Committer
GitHub <noreply@github.com>- Parent
522654a
14 files changed+297 added−4 removed
modified:docs/api.md+27 added
496 unmodified lines497 Converts the subprocess to a duplex stream.498 499 [More info.](streams.md#converting-a-subprocess-to-a-stream)500 501+### subprocess.readableStream(readableOptions?)502+503+`readableOptions`: [`ReadableOptions`](#readableoptions)\504+_Returns_: [`ReadableStream`](https://developer.mozilla.org/en-US/docs/Web/API/ReadableStream) web stream505+506+Converts the subprocess to a readable web stream.507+508+[More info.](streams.md#converting-a-subprocess-to-a-web-stream)509+510+### subprocess.writableStream(writableOptions?)511+512+`writableOptions`: [`WritableOptions`](#writableoptions)\513+_Returns_: [`WritableStream`](https://developer.mozilla.org/en-US/docs/Web/API/WritableStream) web stream514+515+Converts the subprocess to a writable web stream.516+517+[More info.](streams.md#converting-a-subprocess-to-a-web-stream)518+519+### subprocess.transformStream(duplexOptions?)520+521+`duplexOptions`: [`ReadableOptions | WritableOptions`](#readableoptions)\522+_Returns_: [`{readable: ReadableStream, writable: WritableStream}`](https://developer.mozilla.org/en-US/docs/Web/API/TransformStream)523+524+Converts the subprocess to a [`{readable, writable}`](https://developer.mozilla.org/en-US/docs/Web/API/TransformStream) pair of web streams.525+526+[More info.](streams.md#converting-a-subprocess-to-a-web-stream)527+528 ## Result529 530 _TypeScript:_ [`Result`](typescript.md) or [`SyncResult`](typescript.md)\531 _Type:_ `object`805 unmodified linesmodified:docs/streams.md+14 added
116 unmodified linesExpand all117118119120121122123124125126127128129130131132133134135136137138139116 unmodified linesExpand allWhen using [`subprocess.readable()`](api.md#subprocessreadablereadableoptions), [`subprocess.writable()`](api.md#subprocesswritablewritableoptions) or [`subprocess.duplex()`](api.md#subprocessduplexduplexoptions), the stream waits for the subprocess to end, and emits an [`error`](https://nodejs.org/api/stream.html#event-error) event if the subprocess [fails](errors.md). This differs from [`subprocess.stdin`](api.md#subprocessstdin), [`subprocess.stdout`](api.md#subprocessstdout) and [`subprocess.stderr`](api.md#subprocessstderr)'s behavior.
This means you do not need to `await` the subprocess' [promise](execution.md#result). On the other hand, you (or the library using the stream) do need to both consume the stream, and handle its `error` event. This can be done by using [`await finished(stream)`](https://nodejs.org/api/stream.html#streamfinishedstream-options), [`await pipeline(..., stream, ...)`](https://nodejs.org/api/stream.html#streampipelinesource-transforms-destination-options) or [`await text(stream)`](https://nodejs.org/api/webstreams.html#streamconsumerstextstream) which throw an exception when the stream errors.
## Converting a subprocess to a web stream
The [`subprocess.readableStream()`](api.md#subprocessreadablestreamreadableoptions), [`subprocess.writableStream()`](api.md#subprocesswritablestreamwritableoptions) and [`subprocess.transformStream()`](api.md#subprocesstransformstreamduplexoptions) methods are the [web streams](#web-streams) counterparts of [`subprocess.readable()`](api.md#subprocessreadablereadableoptions), [`subprocess.writable()`](api.md#subprocesswritablewritableoptions) and [`subprocess.duplex()`](api.md#subprocessduplexduplexoptions). They behave the same way, including [error handling](#error-handling) and the [`from`](api.md#readableoptionsfrom)/[`to`](api.md#writableoptionsto) options, but return a [`ReadableStream`](https://developer.mozilla.org/en-US/docs/Web/API/ReadableStream), a [`WritableStream`](https://developer.mozilla.org/en-US/docs/Web/API/WritableStream) and a [`{readable, writable}`](https://developer.mozilla.org/en-US/docs/Web/API/TransformStream) pair instead of Node.js streams.
This is useful when using a library or API that expects web streams as arguments. In every other situation, the [Node.js stream methods](#converting-a-subprocess-to-a-stream) can be used instead.
```jsconst readableStream = execa`npm run scaffold`.readableStream();
const writableStream = execa`npm run scaffold`.writableStream();
const {readable, writable} = execa`npm run scaffold`.transformStream();```
<hr>
[**Next**: 📞 Inter-process communication](ipc.md)\[**Previous**: 🔀 Piping multiple subprocesses](pipe.md)\[**Top**: Table of contents](../readme.md#documentation)modified:lib/convert/add.js+4 added
12345678910111213141516171819import {initializeConcurrentStreams} from './concurrent.js';import {createReadable} from './readable.js';import {createWritable} from './writable.js';import {createDuplex} from './duplex.js';import {createReadableStream, createWritableStream, createTransformStream} from './web.js';import {createIterable} from './iterable.js';
// Add methods to convert the subprocess to a stream or iterableexport const addConvertedStreams = (subprocess, {encoding}) => { const concurrentStreams = initializeConcurrentStreams(); subprocess.readable = createReadable.bind(undefined, {subprocess, concurrentStreams, encoding}); subprocess.writable = createWritable.bind(undefined, {subprocess, concurrentStreams}); subprocess.duplex = createDuplex.bind(undefined, {subprocess, concurrentStreams, encoding}); subprocess.readableStream = createReadableStream.bind(undefined, subprocess); subprocess.writableStream = createWritableStream.bind(undefined, subprocess); subprocess.transformStream = createTransformStream.bind(undefined, subprocess); subprocess.iterable = createIterable.bind(undefined, subprocess, encoding); subprocess[Symbol.asyncIterator] = createIterable.bind(undefined, subprocess, encoding, {});};added:lib/convert/web.js+7 added
1234567import {Readable, Writable, Duplex} from 'node:stream';
// Web stream versions of `subprocess.readable()`, `subprocess.writable()` and `subprocess.duplex()`.// They wrap those methods with `.toWeb()`, so all error and abort handling is reused as is.export const createReadableStream = (subprocess, readableOptions) => Readable.toWeb(subprocess.readable(readableOptions));export const createWritableStream = (subprocess, writableOptions) => Writable.toWeb(subprocess.writable(writableOptions));export const createTransformStream = (subprocess, duplexOptions) => Duplex.toWeb(subprocess.duplex(duplexOptions));modified:lib/pipe/setup.js+3 added-1 removed
1 unmodified line2 import {SUBPROCESS_OPTIONS} from '../arguments/fd-options.js';3 import {initializeConcurrentStreams} from '../convert/concurrent.js';4 import {createIterable} from '../convert/iterable.js';5 import {createReadable} from '../convert/readable.js';6+import {createReadableStream} from '../convert/web.js';7 import {internalGetOneMessageOptions} from '../ipc/get-one.js';8 import {internalGetEachMessageOptions} from '../ipc/get-each.js';9 import {normalizePipeArguments} from './pipe-arguments.js';10 import {handlePipeArgumentsError} from './throw.js';49 unmodified lines60 subprocess: promise,61 concurrentStreams,62 encoding,63 });64+ promise.readableStream = createReadableStream.bind(undefined, promise);65 forwardAll(promise, destination);66 };67 68 const forwardAll = (promise, destination) => {107 unmodified lines176 controller.abort();177 }, {once: true, signal: controller.signal});178 };179 178-// `writable()` and `duplex()` are intentionally not forwarded: they write to the destination's `stdin`, which is already being piped from the source.180+// `writable()`, `duplex()`, `writableStream()` and `transformStream()` are intentionally not forwarded: they write to the destination's `stdin`, which is already being piped from the source.181 182 // Asynchronous logic when piping subprocesses183 const handlePipePromise = async ({184 sourcePromise,46 unmodified linesmodified:lib/return/early-error.js+11 added-1 removed
14 unmodified lines15 cleanupCustomStreams(fileDescriptors);16 17 const subprocess = new ChildProcess();18 createDummyStreams(subprocess, fileDescriptors);19- Object.assign(subprocess, {readable, writable, duplex});19+ Object.assign(subprocess, {20+ readable,21+ writable,22+ duplex,23+ readableStream,24+ writableStream,25+ transformStream,26+ });27 28 const earlyError = makeEarlyError({29 error,30 command,31 unmodified lines62 63 const readable = () => new Readable({read() {}});64 const writable = () => new Writable({write() {}});65 const duplex = () => new Duplex({read() {}, write() {}});66+const readableStream = () => Readable.toWeb(readable());67+const writableStream = () => Writable.toWeb(writable());68+const transformStream = () => Duplex.toWeb(duplex());69 70 const handleDummyPromise = async (error, verboseInfo, options) => handleResult(error, verboseInfo, options);added:test/convert/web.js+104 added
1+import {ReadableStream, WritableStream} from 'node:stream/web';2+import test from 'ava';3+import {execa} from '../../index.js';4+import {setFixtureDirectory} from '../helpers/fixtures-directory.js';5+import {6+ assertStreamOutput,7+ assertStreamReadError,8+ assertSubprocessOutput,9+ assertSubprocessError,10+ assertPromiseError,11+ getReadableSubprocess,12+ getWritableSubprocess,13+ getReadWriteSubprocess,14+} from '../helpers/convert.js';15+import {foobarString} from '../helpers/input.js';16+17+setFixtureDirectory();18+19+const writeToStream = async (stream, input = foobarString) => {20+ const writer = stream.getWriter();21+ await writer.write(new TextEncoder().encode(input));22+ await writer.close();23+};24+25+test('.readableStream() success', async t => {26+ const subprocess = getReadableSubprocess();27+ const stream = subprocess.readableStream();28+29+ t.true(stream instanceof ReadableStream);30+31+ await assertStreamOutput(t, stream);32+ await assertSubprocessOutput(t, subprocess);33+});34+35+test('.readableStream() can use from', async t => {36+ const subprocess = execa('noop-fd.js', ['2', foobarString]);37+ const stream = subprocess.readableStream({from: 'stderr'});38+39+ await assertStreamOutput(t, stream);40+});41+42+test('.writableStream() success', async t => {43+ const subprocess = getWritableSubprocess();44+ const stream = subprocess.writableStream();45+46+ t.true(stream instanceof WritableStream);47+48+ await writeToStream(stream);49+ await assertSubprocessOutput(t, subprocess, foobarString, 2);50+});51+52+test('.writableStream() can use to', async t => {53+ const subprocess = execa('stdin-fd.js', ['0']);54+ const stream = subprocess.writableStream({to: 'stdin'});55+56+ await writeToStream(stream);57+ await assertSubprocessOutput(t, subprocess);58+});59+60+test('.transformStream() success', async t => {61+ const subprocess = getReadWriteSubprocess();62+ const {readable, writable} = subprocess.transformStream();63+64+ t.true(readable instanceof ReadableStream);65+ t.true(writable instanceof WritableStream);66+67+ await writeToStream(writable);68+ await assertStreamOutput(t, readable);69+ await assertSubprocessOutput(t, subprocess);70+});71+72+test('subprocess fail -> .readableStream() error', async t => {73+ const subprocess = getReadWriteSubprocess();74+ const stream = subprocess.readableStream();75+76+ const cause = new Error(foobarString);77+ subprocess.kill(cause);78+79+ await assertStreamReadError(t, stream, {cause});80+ await assertSubprocessError(t, subprocess, {cause});81+});82+83+test('subprocess fail -> .writableStream() error', async t => {84+ const subprocess = getReadWriteSubprocess();85+ const stream = subprocess.writableStream();86+ const writer = stream.getWriter();87+88+ const cause = new Error(foobarString);89+ subprocess.kill(cause);90+91+ await assertPromiseError(t, writer.closed, {cause});92+ await assertSubprocessError(t, subprocess, {cause});93+});94+95+test('subprocess fail -> .transformStream() error', async t => {96+ const subprocess = getReadWriteSubprocess();97+ const {readable} = subprocess.transformStream();98+99+ const cause = new Error(foobarString);100+ subprocess.kill(cause);101+102+ await assertStreamReadError(t, readable, {cause});103+ await assertSubprocessError(t, subprocess, {cause});104+});modified:test/pipe/methods.js+12 added
64 unmodified lines65 test('The .pipe() return value has a .readable() method', async t => {66 t.is(await text(pipeSimple().readable()), simpleFull);67 });68 69+test('The .pipe() return value has a .readableStream() method', async t => {70+ t.is(await text(pipeSimple().readableStream()), simpleFull);71+});72+73 test('The .pipe() return value .readable() can be called multiple times', async t => {74 const piped = pipeSimple();75 const [output, secondOutput] = await Promise.all([76 text(piped.readable()),17 unmodified lines94 test('The .pipe() return value does not have a .writable() method', async t => {95 const piped = pipeSimple();96 t.is(piped.writable, undefined);97 t.is(piped.duplex, undefined);98+ t.is(piped.writableStream, undefined);99+ t.is(piped.transformStream, undefined);100 await piped;101 });102 103 test('The .pipe() return value does not have .all unless destination uses the "all" option', async t => {276 unmodified lines380 381 await t.throwsAsync(text(piped.readable()), {message: /Command failed with exit code 2/});382 });383 384+test('The .pipe() return value .readableStream() waits for source failure', async t => {385+ const piped = execa('fail.js').pipe('stdin.js');386+387+ await t.throwsAsync(text(piped.readableStream()), {message: /Command failed with exit code 2/});388+});389+390 test('The .pipe() return value .all waits for source failure', async t => {391 const piped = execa('fail.js').pipe('stdin.js', {all: true});392 393 await t.throwsAsync(text(piped.all), {message: /Command failed with exit code 2/});54 unmodified linesmodified:test/return/early-error.js+10 added
101 unmodified lines102 test('child_process.spawn() early errors can use .readable()', testEarlyErrorConvertor, 'readable');103 test('child_process.spawn() early errors can use .writable()', testEarlyErrorConvertor, 'writable');104 test('child_process.spawn() early errors can use .duplex()', testEarlyErrorConvertor, 'duplex');105 106+const testEarlyErrorWebConvertor = async (t, streamMethod) => {107+ const subprocess = getEarlyErrorSubprocess();108+ subprocess[streamMethod]();109+ await t.throwsAsync(subprocess);110+};111+112+test('child_process.spawn() early errors can use .readableStream()', testEarlyErrorWebConvertor, 'readableStream');113+test('child_process.spawn() early errors can use .writableStream()', testEarlyErrorWebConvertor, 'writableStream');114+test('child_process.spawn() early errors can use .transformStream()', testEarlyErrorWebConvertor, 'transformStream');115+116 const testEarlyErrorStream = async (t, getStreamProperty, options) => {117 const subprocess = getEarlyErrorSubprocess(options);118 const stream = getStreamProperty(subprocess);119 stream.on('close', () => {});11 unmodified linesadded:test-d/convert/readable-stream.test-d.ts+26 added
1+import type {ReadableStream} from 'node:stream/web';2+import {expectType, expectError} from 'tsd';3+import {execa} from '../../index.js';4+5+const subprocess = execa('unicorns');6+7+expectType<ReadableStream>(subprocess.readableStream());8+9+subprocess.readableStream({from: 'stdout'});10+subprocess.readableStream({from: 'stderr'});11+subprocess.readableStream({from: 'all'});12+subprocess.readableStream({from: 'fd3'});13+expectError(subprocess.readableStream({from: 'fd3' as string}));14+expectError(subprocess.readableStream({from: 'stdin'}));15+expectError(subprocess.readableStream({from: 'fd'}));16+expectError(subprocess.readableStream({from: 'fdNotANumber'}));17+expectError(subprocess.readableStream({to: 'stdin'}));18+19+subprocess.readableStream({binary: false});20+expectError(subprocess.readableStream({binary: 'false'}));21+22+subprocess.readableStream({preserveNewlines: false});23+expectError(subprocess.readableStream({preserveNewlines: 'false'}));24+25+expectError(subprocess.readableStream('stdout'));26+expectError(subprocess.readableStream({other: 'stdout'}));added:test-d/convert/transform-stream.test-d.ts+32 added
1+import type {ReadableWritablePair} from 'node:stream/web';2+import {expectType, expectError} from 'tsd';3+import {execa} from '../../index.js';4+5+const subprocess = execa('unicorns');6+7+expectType<ReadableWritablePair>(subprocess.transformStream());8+9+subprocess.transformStream({from: 'stdout'});10+subprocess.transformStream({from: 'stderr'});11+subprocess.transformStream({from: 'all'});12+subprocess.transformStream({from: 'fd3'});13+subprocess.transformStream({to: 'fd3'});14+subprocess.transformStream({from: 'stdout', to: 'stdin'});15+subprocess.transformStream({from: 'stdout', to: 'fd3'});16+expectError(subprocess.transformStream({from: 'stdout' as string}));17+expectError(subprocess.transformStream({to: 'fd3' as string}));18+expectError(subprocess.transformStream({from: 'stdin'}));19+expectError(subprocess.transformStream({from: 'stderr', to: 'stdout'}));20+expectError(subprocess.transformStream({from: 'fd'}));21+expectError(subprocess.transformStream({from: 'fdNotANumber'}));22+expectError(subprocess.transformStream({to: 'fd'}));23+expectError(subprocess.transformStream({to: 'fdNotANumber'}));24+25+subprocess.transformStream({binary: false});26+expectError(subprocess.transformStream({binary: 'false'}));27+28+subprocess.transformStream({preserveNewlines: false});29+expectError(subprocess.transformStream({preserveNewlines: 'false'}));30+31+expectError(subprocess.transformStream('stdout'));32+expectError(subprocess.transformStream({other: 'stdout'}));added:test-d/convert/writable-stream.test-d.ts+25 added
1+import type {WritableStream} from 'node:stream/web';2+import {expectType, expectError} from 'tsd';3+import {execa} from '../../index.js';4+5+const subprocess = execa('unicorns');6+7+expectType<WritableStream>(subprocess.writableStream());8+9+subprocess.writableStream({to: 'stdin'});10+subprocess.writableStream({to: 'fd3'});11+expectError(subprocess.writableStream({to: 'fd3' as string}));12+expectError(subprocess.writableStream({to: 'stdout'}));13+expectError(subprocess.writableStream({to: 'fd'}));14+expectError(subprocess.writableStream({to: 'fdNotANumber'}));15+expectError(subprocess.writableStream({from: 'stdout'}));16+17+expectError(subprocess.writableStream({binary: false}));18+19+expectError(subprocess.writableStream({preserveNewlines: false}));20+21+expectError(subprocess.writableStream('stdin'));22+expectError(subprocess.writableStream({other: 'stdin'}));23+24+const inputPipeSubprocess = execa('unicorns', {stdio: ['pipe', 'pipe', 'pipe', {value: 'pipe', input: true}]});25+inputPipeSubprocess.writableStream({to: 'fd3'});modified:test-d/pipe.test-d.ts+5 added-1 removed
1 import {createWriteStream} from 'node:fs';2 import type {Readable} from 'node:stream';3+import type {ReadableStream} from 'node:stream/web';4 import {expectType, expectNotType, expectError} from 'tsd';5 import {6 execa,7 execaSync,261 unmodified lines269 expectType<Uint8Array>(pipeLine);270 }271 272 expectType<Readable>(subprocess.pipe`stdin`.readable());273+expectType<ReadableStream>(subprocess.pipe`stdin`.readableStream());274 275 expectType<Readable>(subprocess.pipe({all: true})`stdin`.all);276 expectType<undefined>(subprocess.pipe`stdin`.all);277 2 unmodified lines280 expectType<Promise<void>>(ipcPipeResult.sendMessage('message'));281 expectType<Promise<Message<'advanced'>>>(ipcPipeResult.getOneMessage());282 expectType<AsyncIterableIterator<Message<'advanced'>>>(ipcPipeResult.getEachMessage());283 282-// `writable()` and `duplex()` write to the destination's `stdin`, which is already piped from the source, so they are not forwarded.284+// `writable()`, `duplex()`, `writableStream()` and `transformStream()` write to the destination's `stdin`, which is already piped from the source, so they are not forwarded.285 expectError(subprocess.pipe`stdin`.writable());286 expectError(subprocess.pipe`stdin`.duplex());287+expectError(subprocess.pipe`stdin`.writableStream());288+expectError(subprocess.pipe`stdin`.transformStream());modified:types/subprocess/subprocess.d.ts+17 added-1 removed
1 import type {ChildProcess} from 'node:child_process';2 import type {SignalConstants} from 'node:os';3 import type {Readable, Writable, Duplex} from 'node:stream';4+import type {ReadableStream, WritableStream, ReadableWritablePair} from 'node:stream/web';5 import type {Options} from '../arguments/options.js';6 import type {Result} from '../return/result.js';7 import type {PipableSubprocess} from '../pipe.js';8 import type {8 unmodified lines17 import type {SubprocessAll} from './all.js';18 19 // Read-side iteration, stream conversion and `all` methods.20 // These are shared between a subprocess and the return value of `subprocess.pipe()`, which forwards them from its destination subprocess.20-// `writable()` and `duplex()` are not included: they write to `stdin`, which the pipe already feeds from its source.21+// `writable()`, `duplex()`, `writableStream()` and `transformStream()` are not included: they write to `stdin`, which the pipe already feeds from its source.22 export type SubprocessResultMethods<OptionsType extends Options = Options> = {23 /**24 Stream combining/interleaving `subprocess.stdout` and `subprocess.stderr`.25 16 unmodified lines42 /**43 Converts the subprocess to a readable stream.44 */45 readable(readableOptions?: ReadableOptions): Readable;46+47+ /**48+ Converts the subprocess to a readable [web stream](https://developer.mozilla.org/en-US/docs/Web/API/ReadableStream).49+ */50+ readableStream(readableOptions?: ReadableOptions): ReadableStream;51 };52 53 type ExecaCustomSubprocess<OptionsType extends Options> =54 & IpcMethods<HasIpc<OptionsType>, OptionsType['serialization']>55 unmodified lines110 /**111 Converts the subprocess to a duplex stream.112 */113 duplex(duplexOptions?: DuplexOptions): Duplex;114+115+ /**116+ Converts the subprocess to a writable [web stream](https://developer.mozilla.org/en-US/docs/Web/API/WritableStream).117+ */118+ writableStream(writableOptions?: WritableOptions): WritableStream;119+120+ /**121+ Converts the subprocess to a [`{readable, writable}`](https://developer.mozilla.org/en-US/docs/Web/API/TransformStream) pair of web streams.122+ */123+ transformStream(duplexOptions?: DuplexOptions): ReadableWritablePair;124 };125 126 /**127 [`child_process` instance](https://nodejs.org/api/child_process.html#child_process_class_childprocess) with additional methods and properties.15 unmodified lines