Skip to content
Myr

Add `binary` and `preserveNewlines` options to `subprocess.readable()` (#922)

Before adoption: this commit came in with the history the project adopted, so no landing records it.

authored by ehmicky · committed by GitHub · parent bedb729 · Browse files · 15 files+375 added−88 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

15 files+375 added−88 removed

  • tests:+166 added−18 removed
  • other:+209 added−70 removed

15 files+375 added−88 removed

modified:lib/convert/concurrent.js+2 added-8 removed
modified:lib/convert/duplex.js+9 added-6 removed
added:lib/convert/loop.js+97 added
1import {on} from 'node:events';2import {getEncodingTransformGenerator} from '../stdio/encoding-transform.js';3import {getSplitLinesGenerator} from '../stdio/split.js';45export const iterateOnStdout = ({subprocessStdout, subprocess, binary, preserveNewlines}) => {6 const controller = new AbortController();7 stopReadingOnExit(subprocess, controller);8 const onStdoutChunk = on(subprocessStdout, 'data', {9 signal: controller.signal,10 highWaterMark: HIGH_WATER_MARK,11 // Backward compatibility with older name for this option12 // See https://github.com/nodejs/node/pull/52080#discussion_r152522786113 // @todo Remove after removing support for Node 2114 highWatermark: HIGH_WATER_MARK,15 });16 const onStdoutData = iterateOnData({subprocessStdout, onStdoutChunk, controller, binary, preserveNewlines});17 return onStdoutData;18};1920const stopReadingOnExit = async (subprocess, controller) => {21 try {22 await subprocess;23 } catch {} finally {24 controller.abort();25 }26};2728// @todo: replace with `getDefaultHighWaterMark(true)` after dropping support for Node <18.17.029export const DEFAULT_OBJECT_HIGH_WATER_MARK = 16;3031// The `highWaterMark` of `events.on()` is measured in number of events, not in bytes.32// Not knowing the average amount of bytes per `data` event, we use the same heuristic as streams in objectMode, since they have the same issue.33// Therefore, we use the value of `getDefaultHighWaterMark(true)`.34// Note: this option does not exist on Node 18, but this is ok since the logic works without it. It just consumes more memory.35const HIGH_WATER_MARK = DEFAULT_OBJECT_HIGH_WATER_MARK;3637const iterateOnData = async function * ({subprocessStdout, onStdoutChunk, controller, binary, preserveNewlines}) {38 const {39 encodeChunk = identityGenerator,40 encodeChunkFinal = noopGenerator,41 splitLines = identityGenerator,42 splitLinesFinal = noopGenerator,43 } = getTransforms({subprocessStdout, binary, preserveNewlines});4445 try {46 for await (const [chunk] of onStdoutChunk) {47 yield * handleChunk(encodeChunk, splitLines, chunk);48 }49 } catch (error) {50 if (!controller.signal.aborted) {51 throw error;52 }53 } finally {54 yield * handleFinalChunks(encodeChunkFinal, splitLines, splitLinesFinal);55 }56};5758const getTransforms = ({subprocessStdout, binary, preserveNewlines}) => {59 if (subprocessStdout.readableObjectMode) {60 return {};61 }6263 const writableObjectMode = false;6465 if (!binary) {66 return getTextTransforms(binary, preserveNewlines, writableObjectMode);67 }6869 return {};70};7172const getTextTransforms = (binary, preserveNewlines, writableObjectMode) => {73 const encoding = 'utf8';74 const {transform: encodeChunk, final: encodeChunkFinal} = getEncodingTransformGenerator(encoding, writableObjectMode, false);75 const {transform: splitLines, final: splitLinesFinal} = getSplitLinesGenerator({encoding, binary, preserveNewlines, writableObjectMode, state: {}});76 return {encodeChunk, encodeChunkFinal, splitLines, splitLinesFinal};77};7879const identityGenerator = function * (chunk) {80 yield chunk;81};8283const noopGenerator = function * () {};8485const handleChunk = function * (encodeChunk, splitLines, chunk) {86 for (const chunkString of encodeChunk(chunk)) {87 yield * splitLines(chunkString);88 }89};9091const handleFinalChunks = function * (encodeChunkFinal, splitLines, splitLinesFinal) {92 for (const chunkString of encodeChunkFinal()) {93 yield * splitLines(chunkString);94 }9596 yield * splitLinesFinal();97};
modified:lib/convert/readable.js+26 added-37 removed
modified:lib/convert/shared.js+8 added
42 unmodified lines
43 } else if (isOpen) {44 stream.destroy();45 }46};4748export const createDeferred = () => {49 let resolve;50 const promise = new Promise(resolve_ => {51 resolve = resolve_;52 });53 return Object.assign(promise, {resolve});54};
added:test/convert/loop.js+137 added
1import {once} from 'node:events';2import {getDefaultHighWaterMark} from 'node:stream';3import test from 'ava';4import {setFixtureDir} from '../helpers/fixtures-dir.js';5import {6 assertStreamOutput,7 assertStreamChunks,8 assertSubprocessOutput,9 getReadableSubprocess,10 getReadWriteSubprocess,11} from '../helpers/convert.js';12import {13 simpleFull,14 simpleChunks,15 simpleChunksBuffer,16 simpleLines,17 noNewlinesFull,18 complexFull,19 singleComplexBuffer,20 complexChunks,21 complexChunksEnd,22} from '../helpers/lines.js';23import {outputObjectGenerator, getOutputGenerator} from '../helpers/generator.js';24import {foobarString, foobarObject} from '../helpers/input.js';25import {multibyteChar, multibyteUint8Array, breakingLength, brokenSymbol} from '../helpers/encoding.js';2627setFixtureDir();2829const foobarObjectChunks = [foobarObject, foobarObject, foobarObject];3031const getSubprocess = (methodName, output, options) => {32 if (methodName !== 'duplex') {33 return getReadableSubprocess(output, options);34 }3536 const subprocess = getReadWriteSubprocess(options);37 subprocess.stdin.end(output);38 return subprocess;39};4041// eslint-disable-next-line max-params42const testText = async (t, expectedChunks, methodName, binary, preserveNewlines) => {43 const subprocess = getSubprocess(methodName, complexFull);44 const stream = subprocess[methodName]({binary, preserveNewlines});4546 await assertStreamChunks(t, stream, expectedChunks);47 await assertSubprocessOutput(t, subprocess, complexFull);48};4950test('.readable() can use "binary: true"', testText, singleComplexBuffer, 'readable', true, undefined);51test('.readable() can use "binary: undefined"', testText, singleComplexBuffer, 'readable', undefined, undefined);52test('.readable() can use "binary: false"', testText, complexChunksEnd, 'readable', false, undefined);53test('.readable() can use "binary: false" + "preserveNewlines: true"', testText, complexChunksEnd, 'readable', false, true);54test('.readable() can use "binary: false" + "preserveNewlines: false"', testText, complexChunks, 'readable', false, false);55test('.duplex() can use "binary: true"', testText, singleComplexBuffer, 'duplex', true, undefined);56test('.duplex() can use "binary: undefined"', testText, singleComplexBuffer, 'duplex', undefined, undefined);57test('.duplex() can use "binary: false"', testText, complexChunksEnd, 'duplex', false, undefined);58test('.duplex() can use "binary: false" + "preserveNewlines: true"', testText, complexChunksEnd, 'duplex', false, true);59test('.duplex() can use "binary: false" + "preserveNewlines: false"', testText, complexChunks, 'duplex', false, false);6061const testTextOutput = async (t, expectedOutput, methodName, preserveNewlines) => {62 const subprocess = getSubprocess(methodName, complexFull);63 const stream = subprocess[methodName]({binary: false, preserveNewlines});6465 await assertStreamOutput(t, stream, expectedOutput);66 await assertSubprocessOutput(t, subprocess, complexFull);67};6869test('.readable() "binary: false" keeps output as is', testTextOutput, complexFull, 'readable', undefined);70test('.readable() "binary: false" + "preserveNewlines: true" keeps output as is', testTextOutput, complexFull, 'readable', true);71test('.readable() "binary: false" + "preserveNewlines: false" removes all newlines', testTextOutput, noNewlinesFull, 'readable', false);72test('.duplex() "binary: false" keeps output as is', testTextOutput, complexFull, 'duplex', undefined);73test('.duplex() "binary: false" + "preserveNewlines: true" keeps output as is', testTextOutput, complexFull, 'duplex', true);74test('.duplex() "binary: false" + "preserveNewlines: false" removes all newlines', testTextOutput, noNewlinesFull, 'duplex', false);7576// eslint-disable-next-line max-params77const testObjectMode = async (t, expectedChunks, methodName, encoding, initialObjectMode, finalObjectMode, binary, options) => {78 const subprocess = getSubprocess(methodName, simpleFull, options);79 if (encoding !== null) {80 subprocess.stdout.setEncoding(encoding);81 }8283 t.is(subprocess.stdout.readableEncoding, encoding);84 t.is(subprocess.stdout.readableObjectMode, initialObjectMode);85 t.is(subprocess.stdout.readableHighWaterMark, getDefaultHighWaterMark(initialObjectMode));8687 const stream = subprocess[methodName]({binary, preserveNewlines: true});88 t.is(stream.readableEncoding, encoding);89 t.is(stream.readableObjectMode, finalObjectMode);90 t.is(stream.readableHighWaterMark, getDefaultHighWaterMark(finalObjectMode));91 t.is(subprocess.stdout.readableEncoding, encoding);92 t.is(subprocess.stdout.readableObjectMode, initialObjectMode);93 t.is(subprocess.stdout.readableHighWaterMark, getDefaultHighWaterMark(initialObjectMode));9495 await assertStreamChunks(t, stream, expectedChunks);96 await subprocess;97};9899test('.readable() uses Buffers with "binary: true"', testObjectMode, simpleChunksBuffer, 'readable', null, false, false, true);100test('.readable() uses strings with "binary: true" and .setEncoding("utf8")', testObjectMode, simpleChunks, 'readable', 'utf8', false, false, true);101test('.readable() uses strings with "binary: true" and "encoding: buffer"', testObjectMode, simpleChunks, 'readable', 'utf8', false, false, true, {encoding: 'buffer'});102test('.readable() uses strings in objectMode with "binary: true" and object transforms', testObjectMode, foobarObjectChunks, 'readable', null, true, true, true, {stdout: outputObjectGenerator});103test('.readable() uses strings in objectMode with "binary: false"', testObjectMode, simpleLines, 'readable', null, false, true, false);104test('.readable() uses strings in objectMode with "binary: false" and .setEncoding("utf8")', testObjectMode, simpleLines, 'readable', 'utf8', false, true, false);105test('.readable() uses strings in objectMode with "binary: false" and "encoding: buffer"', testObjectMode, simpleLines, 'readable', 'utf8', false, true, false, {encoding: 'buffer'});106test('.readable() uses strings in objectMode with "binary: false" and object transforms', testObjectMode, foobarObjectChunks, 'readable', null, true, true, false, {stdout: outputObjectGenerator});107test('.duplex() uses Buffers with "binary: true"', testObjectMode, simpleChunksBuffer, 'duplex', null, false, false, true);108test('.duplex() uses strings with "binary: true" and .setEncoding("utf8")', testObjectMode, simpleChunks, 'duplex', 'utf8', false, false, true);109test('.duplex() uses strings with "binary: true" and "encoding: buffer"', testObjectMode, simpleChunks, 'duplex', 'utf8', false, false, true, {encoding: 'buffer'});110test('.duplex() uses strings in objectMode with "binary: true" and object transforms', testObjectMode, foobarObjectChunks, 'duplex', null, true, true, true, {stdout: outputObjectGenerator});111test('.duplex() uses strings in objectMode with "binary: false"', testObjectMode, simpleLines, 'duplex', null, false, true, false);112test('.duplex() uses strings in objectMode with "binary: false" and .setEncoding("utf8")', testObjectMode, simpleLines, 'duplex', 'utf8', false, true, false);113test('.duplex() uses strings in objectMode with "binary: false" and "encoding: buffer"', testObjectMode, simpleLines, 'duplex', 'utf8', false, true, false, {encoding: 'buffer'});114test('.duplex() uses strings in objectMode with "binary: false" and object transforms', testObjectMode, foobarObjectChunks, 'duplex', null, true, true, false, {stdout: outputObjectGenerator});115116const testObjectSplit = async (t, methodName) => {117 const subprocess = getSubprocess(methodName, foobarString, {stdout: getOutputGenerator(simpleFull, true)});118 const stream = subprocess[methodName]({binary: false});119 await assertStreamChunks(t, stream, [simpleFull]);120 await subprocess;121};122123test('.readable() "binary: false" does not split lines of strings produced by object transforms', testObjectSplit, 'readable');124test('.duplex() "binary: false" does not split lines of strings produced by object transforms', testObjectSplit, 'duplex');125126const testMultibyteCharacters = async (t, methodName) => {127 const subprocess = getReadWriteSubprocess();128 const stream = subprocess[methodName]({binary: false});129 const assertPromise = assertStreamOutput(t, stream, `${multibyteChar}${brokenSymbol}`);130 subprocess.stdin.write(multibyteUint8Array.slice(0, breakingLength));131 await once(subprocess.stdout, 'data');132 subprocess.stdin.end();133 await assertPromise;134};135136test('.readable() "binary: false" handles partial multibyte characters', testMultibyteCharacters, 'readable');137test('.duplex() "binary: false" handles partial multibyte characters', testMultibyteCharacters, 'duplex');
modified:test/convert/readable.js+9 added-8 removed
1import {once} from 'node:events';2import process from 'node:process';3import {compose, Readable, Writable, PassThrough, getDefaultHighWaterMark} from 'node:stream';3import {compose, Readable, Writable, PassThrough} from 'node:stream';4import {pipeline} from 'node:stream/promises';5import {text} from 'node:stream/consumers';6import {setTimeout} from 'node:timers/promises';7import test from 'ava';
4 unmodified lines
12 assertReadableAborted,13 assertWritableAborted,14 assertProcessNormalExit,15 assertStreamOutput,16 assertStreamChunks,17 assertStreamError,18 assertStreamReadError,19 assertSubprocessOutput,20 assertSubprocessError,
226 unmodified lines
247 const stream = subprocess.readable();248 t.true(stream.readableObjectMode);249 t.is(stream.readableHighWaterMark, defaultObjectHighWaterMark);250250 t.deepEqual(await stream.toArray(), [foobarObject]);251 await assertStreamChunks(t, stream, [foobarObject]);252 await assertSubprocessOutput(t, subprocess, [foobarObject]);253});254255test('.duplex() works with objectMode and reads', async t => {
4 unmodified lines
260 t.false(stream.writableObjectMode);261 t.is(stream.writableHighWaterMark, defaultHighWaterMark);262 stream.end(foobarString);263263 t.deepEqual(await stream.toArray(), [foobarObject]);264 await assertStreamChunks(t, stream, [foobarObject]);265 await assertSubprocessOutput(t, subprocess, [foobarObject]);266});267268test('.readable() works with default encoding', async t => {269 const subprocess = getReadableSubprocess();270 const stream = subprocess.readable();271 t.is(stream.readableEncoding, null);272272 t.deepEqual(await stream.toArray(), [foobarBuffer]);273 await assertStreamChunks(t, stream, [foobarBuffer]);274 await assertSubprocessOutput(t, subprocess, foobarString);275});276277test('.duplex() works with default encoding', async t => {
1 unmodified line
279 const stream = subprocess.duplex();280 t.is(stream.readableEncoding, null);281 stream.end(foobarString);282282 t.deepEqual(await stream.toArray(), [foobarBuffer]);283 await assertStreamChunks(t, stream, [foobarBuffer]);284 await assertSubprocessOutput(t, subprocess, foobarString);285});286287test('.readable() works with encoding "utf8"', async t => {
1 unmodified line
289 subprocess.stdout.setEncoding('utf8');290 const stream = subprocess.readable();291 t.is(stream.readableEncoding, 'utf8');292292 t.deepEqual(await stream.toArray(), [foobarString]);293 await assertStreamChunks(t, stream, [foobarString]);294 await assertSubprocessOutput(t, subprocess, foobarString);295});296297test('.duplex() works with encoding "utf8"', async t => {
2 unmodified lines
300 const stream = subprocess.duplex();301 t.is(stream.readableEncoding, 'utf8');302 stream.end(foobarBuffer);303303 t.deepEqual(await stream.toArray(), [foobarString]);304 await assertStreamChunks(t, stream, [foobarString]);305 await assertSubprocessOutput(t, subprocess, foobarString);306});307308test('.readable() has the right highWaterMark', async t => {
119 unmodified lines
428 // eslint-disable-next-line no-await-in-loop429 await Promise.race([onPause, once(subprocess.stdout, 'data')]);430 }431431 const expectedCount = getDefaultHighWaterMark(true) + 1;432 const expectedCount = defaultObjectHighWaterMark + 1;433 const expectedOutput = '.'.repeat(expectedCount);434 t.is(count, expectedCount);435 subprocess.stdin.end();436 await assertStreamOutput(t, stream, expectedOutput);
19 unmodified lines
modified:test/helpers/convert.js+5 added-1 removed
25 unmodified lines
26export const assertStreamOutput = async (t, stream, expectedOutput = foobarString) => {27 t.is(await text(stream), expectedOutput);28};2930export const assertStreamChunks = async (t, stream, expectedOutput) => {31 t.deepEqual(await stream.toArray(), expectedOutput);32};3334export const assertSubprocessOutput = async (t, subprocess, expectedOutput = foobarString, fdNumber = 1) => {35 const result = await subprocess;36 t.deepEqual(result.stdio[fdNumber], expectedOutput);37};
15 unmodified lines
5354 return thrownError;55};5653export const getReadableSubprocess = () => execa('noop-fd.js', ['1', foobarString]);57export const getReadableSubprocess = (output = foobarString, options = {}) => execa('noop-fd.js', ['1', output], options);5859export const getWritableSubprocess = () => execa('noop-stdin-fd.js', ['2']);6061export const getReadWriteSubprocess = options => execa('stdin.js', options);
added:test/helpers/encoding.js+7 added
modified:test/helpers/lines.js+6 added
1import {Buffer} from 'node:buffer';23export const simpleFull = 'aaa\nbbb\nccc';4export const simpleChunks = [simpleFull];5export const simpleChunksBuffer = [Buffer.from(simpleFull)];6export const simpleLines = ['aaa\n', 'bbb\n', 'ccc'];7export const simpleFullEndLines = ['aaa\n', 'bbb\n', 'ccc\n'];8export const noNewlinesFull = 'aaabbbccc';9export const noNewlinesChunks = ['aaa', 'bbb', 'ccc'];10export const complexFull = '\naaa\r\nbbb\n\nccc';11export const singleComplexBuffer = [Buffer.from(complexFull)];12export const complexChunksEnd = ['\n', 'aaa\r\n', 'bbb\n', '\n', 'ccc'];13export const complexChunks = ['', 'aaa', 'bbb', '', 'ccc'];1415const textEncoder = new TextEncoder();16const textDecoder = new TextDecoder();17
17 unmodified lines
modified:test/stdio/encoding-transform.js+1 added-8 removed
4 unmodified lines
5import {setFixtureDir} from '../helpers/fixtures-dir.js';6import {getStdio} from '../helpers/stdio.js';7import {foobarString, foobarUint8Array, foobarBuffer, foobarObject} from '../helpers/input.js';8import {noopGenerator, getOutputGenerator, convertTransformToFinal} from '../helpers/generator.js';9import {multibyteChar, multibyteString, multibyteUint8Array, breakingLength, brokenSymbol} from '../helpers/encoding.js';1011setFixtureDir();1212const textEncoder = new TextEncoder();1313const getTypeofGenerator = (objectMode, binary) => ({14 * transform(line) {15 yield Object.prototype.toString.call(line);16 },
136 unmodified lines
153test('Generator can return final Uint8Array with encoding "buffer", objectMode, failure', testGeneratorReturnType, foobarUint8Array, 'buffer', false, true, true);154test('Generator can return final string with encoding "hex", objectMode, failure', testGeneratorReturnType, foobarString, 'hex', false, true, true);155test('Generator can return final Uint8Array with encoding "hex", objectMode, failure', testGeneratorReturnType, foobarUint8Array, 'hex', false, true, true);156158const multibyteChar = '\u{1F984}';159const multibyteString = `${multibyteChar}${multibyteChar}`;160const multibyteUint8Array = textEncoder.encode(multibyteString);161const breakingLength = multibyteUint8Array.length * 0.75;162const brokenSymbol = '\uFFFD';163157const testMultibyte = async (t, objectMode) => {158 const subprocess = execa('stdin.js', {stdin: noopGenerator(objectMode, true)});159 subprocess.stdin.write(multibyteUint8Array.slice(0, breakingLength));160 await scheduler.yield();
20 unmodified lines
modified:test/stdio/split.js+1 added-1 removed
12 unmodified lines
13 simpleFull,14 simpleChunks,15 simpleLines,16 simpleFullEndLines,17 noNewlinesFull,18 noNewlinesChunks,19 getEncoding,20 stringsToUint8Arrays,21 serializeResult,
6 unmodified lines
28const windowsFull = 'aaa\r\nbbb\r\nccc';29const windowsFullEnd = `${windowsFull}\r\n`;30const windowsChunks = [windowsFull];31const windowsLines = ['aaa\r\n', 'bbb\r\n', 'ccc'];31const noNewlinesFull = 'aaabbbccc';32const noNewlinesFullEnd = `${noNewlinesFull}\n`;33const noNewlinesLines = ['aaabbbccc'];34const singleFull = 'aaa';35const singleFullEnd = `${singleFull}\n`;
293 unmodified lines
modified:index.d.ts+26 added-6 removed
976 unmodified lines
977 pipe<Destination extends ExecaSubprocess>(destination: Destination, options?: PipeOptions):978 Promise<Awaited<Destination>> & PipableSubprocess;979};980981type ReadableStreamOptions = {981type ReadableOptions = {982 /**983 Which stream to read from the subprocess. A file descriptor like `"fd3"` can also be passed.984985 `"all"` reads both `stdout` and `stderr`. This requires the `all` option to be `true`.986987 @default 'stdout'988 */989 readonly from?: FromOption;990991 /**992 If `false`, the stream iterates over lines. Each line is a string. Also, the stream is in [object mode](https://nodejs.org/api/stream.html#object-mode).993994 If `true`, the stream iterates over arbitrary chunks of data. Each line is a [`Buffer`](https://nodejs.org/api/buffer.html#class-buffer).995996 @default true997 */998 readonly binary?: boolean;9991000 /**1001 If both this option and the `binary` option is `false`, newlines are stripped from each line.10021003 @default true1004 */1005 readonly preserveNewlines?: boolean;1006};1007990type WritableStreamOptions = {1008type WritableOptions = {1009 /**1010 Which stream to write to the subprocess. A file descriptor like `"fd3"` can also be passed.10111012 @default 'stdin'1013 */1014 readonly to?: ToOption;1015};1016997type DuplexStreamOptions = ReadableStreamOptions & WritableStreamOptions;1017type DuplexOptions = ReadableOptions & WritableOptions;10181019export type ExecaResultPromise<OptionsType extends Options = Options> = {1020 stdin: StreamUnlessIgnored<'0', OptionsType>;1021
32 unmodified lines
1054 Unlike [`subprocess.stdout`](https://nodejs.org/api/child_process.html#subprocessstdout), 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. This means you do not need to `await` the subprocess' promise. On the other hand, you do need to handle to the stream `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.10551056 Before using this method, please first consider the `stdin`/`stdout`/`stderr`/`stdio` options or the `subprocess.pipe()` method.1057 */1038 readable(streamOptions?: ReadableStreamOptions): Readable;1058 readable(readableOptions?: ReadableOptions): Readable;10591060 /**1061 Converts the subprocess to a writable stream.10621063 Unlike [`subprocess.stdin`](https://nodejs.org/api/child_process.html#subprocessstdin), 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. This means you do not need to `await` the subprocess' promise. On the other hand, you do need to handle to the stream `error` event. This can be done by using [`await finished(stream)`](https://nodejs.org/api/stream.html#streamfinishedstream-options) or [`await pipeline(stream, ...)`](https://nodejs.org/api/stream.html#streampipelinesource-transforms-destination-options) which throw an exception when the stream errors.10641065 Before using this method, please first consider the `stdin`/`stdout`/`stderr`/`stdio` options or the `subprocess.pipe()` method.1066 */1047 writable(streamOptions?: WritableStreamOptions): Writable;1067 writable(writableOptions?: WritableOptions): Writable;10681069 /**1070 Converts the subprocess to a duplex stream.10711072 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. This means you do not need to `await` the subprocess' promise. On the other hand, you do need to handle to the stream `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.10731074 Before using this method, please first consider the `stdin`/`stdout`/`stderr`/`stdio` options or the `subprocess.pipe()` method.1075 */1056 duplex(streamOptions?: DuplexStreamOptions): Duplex;1076 duplex(duplexOptions?: DuplexOptions): Duplex;1077} & PipableSubprocess;10781079export type ExecaSubprocess<OptionsType extends Options = Options> = ChildProcess &1080ExecaResultPromise<OptionsType> &
475 unmodified lines
modified:index.test-d.ts+12 added
275 unmodified lines
276 scriptPromise.readable({from: 'stdout'});277 scriptPromise.readable({from: 'stderr'});278 scriptPromise.readable({from: 'all'});279 scriptPromise.readable({from: 'fd3'});280 scriptPromise.readable({binary: false});281 scriptPromise.readable({preserveNewlines: false});282 expectError(scriptPromise.readable('stdout'));283 expectError(scriptPromise.readable({from: 'stdin'}));284 expectError(scriptPromise.readable({from: 'fd'}));285 expectError(scriptPromise.readable({from: 'fdNotANumber'}));286 expectError(scriptPromise.readable({binary: 'false'}));287 expectError(scriptPromise.readable({preserveNewlines: 'false'}));288 expectError(scriptPromise.readable({to: 'stdin'}));289 expectError(scriptPromise.readable({other: 'stdout'}));290 scriptPromise.writable({});291 scriptPromise.writable({to: 'stdin'});292 scriptPromise.writable({to: 'fd3'});293 expectError(scriptPromise.writable('stdin'));294 expectError(scriptPromise.writable({to: 'stdout'}));295 expectError(scriptPromise.writable({to: 'fd'}));296 expectError(scriptPromise.writable({to: 'fdNotANumber'}));297 expectError(scriptPromise.writable({from: 'stdout'}));298 expectError(scriptPromise.writable({binary: false}));299 expectError(scriptPromise.writable({preserveNewlines: false}));300 expectError(scriptPromise.writable({other: 'stdin'}));301 scriptPromise.duplex({});302 scriptPromise.duplex({from: 'stdout'});303 scriptPromise.duplex({from: 'stderr'});304 scriptPromise.duplex({from: 'all'});305 scriptPromise.duplex({from: 'fd3'});306 scriptPromise.duplex({from: 'stdout', to: 'stdin'});307 scriptPromise.duplex({from: 'stdout', to: 'fd3'});308 scriptPromise.duplex({binary: false});309 scriptPromise.duplex({preserveNewlines: false});310 expectError(scriptPromise.duplex('stdout'));311 expectError(scriptPromise.duplex({from: 'stdin'}));312 expectError(scriptPromise.duplex({from: 'stderr', to: 'stdout'}));313 expectError(scriptPromise.duplex({from: 'fd'}));314 expectError(scriptPromise.duplex({from: 'fdNotANumber'}));315 expectError(scriptPromise.duplex({to: 'fd'}));316 expectError(scriptPromise.duplex({to: 'fdNotANumber'}));317 expectError(scriptPromise.duplex({binary: 'false'}));318 expectError(scriptPromise.duplex({preserveNewlines: 'false'}));319 expectError(scriptPromise.duplex({other: 'stdout'}));320321 expectType<Readable>(execaPromise.all);322 const noAllPromise = execa('unicorns');
1350 unmodified lines
modified:readme.md+29 added-13 removed
436 unmodified lines
437When an error is passed as argument, it is set to the subprocess' [`error.cause`](#cause). The subprocess is then terminated with the default signal. This does not emit the [`error` event](https://nodejs.org/api/child_process.html#event-error).438439[More info.](https://nodejs.org/api/child_process.html#subprocesskillsignal)440441#### readable(streamOptions?)441#### readable(readableOptions?)442443`streamOptions`: [`StreamOptions`](#streamoptions)\443`readableOptions`: [`ReadableOptions`](#readableoptions)\444_Returns_: [`Readable`](https://nodejs.org/api/stream.html#class-streamreadable) Node.js stream445446Converts the subprocess to a readable stream.447448Unlike [`subprocess.stdout`](https://nodejs.org/api/child_process.html#subprocessstdout), 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](#subprocessresult). This means you do not need to `await` the subprocess' [promise](#subprocess). On the other hand, you do need to handle to the stream `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.449450Before using this method, please first consider the [`stdin`](#stdin)/[`stdout`](#stdout-1)/[`stderr`](#stderr-1)/[`stdio`](#stdio-1) options or the [`subprocess.pipe()`](#pipefile-arguments-options) method.451452#### writable(streamOptions?)452#### writable(writableOptions?)453454`streamOptions`: [`StreamOptions`](#streamoptions)\454`writableOptions`: [`WritableOptions`](#writableoptions)\455_Returns_: [`Writable`](https://nodejs.org/api/stream.html#class-streamwritable) Node.js stream456457Converts the subprocess to a writable stream.458459Unlike [`subprocess.stdin`](https://nodejs.org/api/child_process.html#subprocessstdin), 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](#subprocessresult). This means you do not need to `await` the subprocess' [promise](#subprocess). On the other hand, you do need to handle to the stream `error` event. This can be done by using [`await finished(stream)`](https://nodejs.org/api/stream.html#streamfinishedstream-options) or [`await pipeline(stream, ...)`](https://nodejs.org/api/stream.html#streampipelinesource-transforms-destination-options) which throw an exception when the stream errors.460461Before using this method, please first consider the [`stdin`](#stdin)/[`stdout`](#stdout-1)/[`stderr`](#stderr-1)/[`stdio`](#stdio-1) options or the [`subprocess.pipe()`](#pipefile-arguments-options) method.462463#### duplex(streamOptions?)463#### duplex(duplexOptions?)464465`streamOptions`: [`StreamOptions`](#streamoptions)\465`duplexOptions`: [`ReadableOptions | WritableOptions`](#readableoptions)\466_Returns_: [`Duplex`](https://nodejs.org/api/stream.html#class-streamduplex) Node.js stream467468Converts the subprocess to a duplex stream.469470The stream waits for the subprocess to end and emits an [`error`](https://nodejs.org/api/stream.html#event-error) event if the subprocess [fails](#subprocessresult). This means you do not need to `await` the subprocess' [promise](#subprocess). On the other hand, you do need to handle to the stream `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.471472Before using this method, please first consider the [`stdin`](#stdin)/[`stdout`](#stdout-1)/[`stderr`](#stderr-1)/[`stdio`](#stdio-1) options or the [`subprocess.pipe()`](#pipefile-arguments-options) method.473474##### streamOptions474##### readableOptions475476Type: `object`477478##### streamOptions.from478##### readableOptions.from479480Type: `"stdout" | "stderr" | "all" | "fd3" | "fd4" | ...`\481Default: `"stdout"`482483Which stream to read from the subprocess. A file descriptor like `"fd3"` can also be passed.484485`"all"` reads both `stdout` and `stderr`. This requires the [`all` option](#all-2) to be `true`.486487Only available with [`.readable()`](#readablestreamoptions) and [`.duplex()`](#duplexstreamoptions), not [`.writable()`](#writablestreamoptions).487##### readableOptions.binary488489##### streamOptions.to489Type: `boolean`\490Default: `true`491492If `false`, the stream iterates over lines. Each line is a string. Also, the stream is in [object mode](https://nodejs.org/api/stream.html#object-mode).493494If `true`, the stream iterates over arbitrary chunks of data. Each line is a [`Buffer`](https://nodejs.org/api/buffer.html#class-buffer).495496##### readableOptions.preserveNewlines497498Type: `boolean`\499Default: `true`500501If both this option and the [`binary` option](#readableoptionsbinary) is `false`, newlines are stripped from each line.502503##### writableOptions504505Type: `object`506507##### writableOptions.to508509Type: `"stdin" | "fd3" | "fd4" | ...`\510Default: `"stdin"`511512Which stream to write to the subprocess. A file descriptor like `"fd3"` can also be passed.513496Only available with [`.writable()`](#writablestreamoptions) and [`.duplex()`](#duplexstreamoptions), not [`.readable()`](#readablestreamoptions).497514### SubprocessResult515516Type: `object`517
398 unmodified lines
916Default: `false`917918Split `stdout` and `stderr` into lines.919- [`result.stdout`](#stdout), [`result.stderr`](#stderr), [`result.all`](#all-1) and [`result.stdio`](#stdio) are arrays of lines.904- [`subprocess.stdout`](https://nodejs.org/api/child_process.html#subprocessstdout), [`subprocess.stderr`](https://nodejs.org/api/child_process.html#subprocessstderr), [`subprocess.all`](#all), [`subprocess.stdio`](https://nodejs.org/api/child_process.html#subprocessstdio), [`subprocess.readable()`](#readablestreamoptions) and [`subprocess.duplex`](#duplexstreamoptions) iterate over lines instead of arbitrary chunks.920- [`subprocess.stdout`](https://nodejs.org/api/child_process.html#subprocessstdout), [`subprocess.stderr`](https://nodejs.org/api/child_process.html#subprocessstderr), [`subprocess.all`](#all), [`subprocess.stdio`](https://nodejs.org/api/child_process.html#subprocessstdio), [`subprocess.readable()`](#readablereadableoptions) and [`subprocess.duplex`](#duplexduplexoptions) iterate over lines instead of arbitrary chunks.921- Any stream passed to the [`stdout`](#stdout-1), [`stderr`](#stderr-1) or [`stdio`](#stdio-1) option receives lines instead of arbitrary chunks.922923#### encoding924
258 unmodified lines