Skip to content
Myr

Make subprocess async iterable (#923)

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

authored by ehmicky · committed by GitHub · parent 56ee48e · Browse files · 19 files+629 added−78 removed
This commit

State

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

Diff stats

19 files+629 added−78 removed

  • tests:+409 added−51 removed
  • other:+220 added−27 removed

19 files+629 added−78 removed

modified:docs/scripts.md+27 added
459 unmodified lines
460// Execa461await $({inputFile: 'file.txt'})`cat`462```463464### Iterate over output lines465466```sh467# Bash468while read469do470 if [[ "$REPLY" == *ERROR* ]]471 then472 echo "$REPLY"473 fi474done < <(npm run build)475```476477```js478// zx does not allow proper iteration.479// For example, the iteration does not handle subprocess errors.480```481482```js483// Execa484for await (const line of $`npm run build`) {485 if (line.includes('ERROR')) {486 console.log(line);487 }488}489```490491### Errors492493```sh494# Bash communicates errors only through the exit code and stderr
337 unmodified lines
modified:docs/transform.md+14 added-1 removed
modified:lib/convert/add.js+4 added-1 removed
1import {initializeConcurrentStreams} from './concurrent.js';2import {createReadable} from './readable.js';3import {createWritable} from './writable.js';4import {createDuplex} from './duplex.js';5import {createIterable} from './iterable.js';66export const addConvertedStreams = subprocess => {7export const addConvertedStreams = (subprocess, options) => {8 const concurrentStreams = initializeConcurrentStreams();9 subprocess.readable = createReadable.bind(undefined, {subprocess, concurrentStreams});10 subprocess.writable = createWritable.bind(undefined, {subprocess, concurrentStreams});11 subprocess.duplex = createDuplex.bind(undefined, {subprocess, concurrentStreams});12 subprocess.iterable = createIterable.bind(undefined, subprocess, options);13 subprocess[Symbol.asyncIterator] = createIterable.bind(undefined, subprocess, options, {});14};
added:lib/convert/iterable.js+24 added
1import {getReadable} from '../pipe/validate.js';2import {iterateOnStdout} from './loop.js';34export const createIterable = (subprocess, {encoding}, {5 from,6 binary = encoding === 'buffer',7 preserveNewlines = false,8} = {}) => {9 const subprocessStdout = getReadable(subprocess, from);10 const onStdoutData = iterateOnStdout({subprocessStdout, subprocess, binary, preserveNewlines, isStream: false});11 return iterateOnStdoutData(onStdoutData, subprocessStdout, subprocess);12};1314const iterateOnStdoutData = async function * (onStdoutData, subprocessStdout, subprocess) {15 try {16 yield * onStdoutData;17 } finally {18 if (subprocessStdout.readable) {19 subprocessStdout.destroy();20 }2122 await subprocess;23 }24};
modified:lib/convert/loop.js+16 added-10 removed
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}) => {5export const iterateOnStdout = ({subprocessStdout, subprocess, binary, preserveNewlines, isStream}) => {6 const controller = new AbortController();7 stopReadingOnExit(subprocess, controller);8 const onStdoutChunk = on(subprocessStdout, 'data', {9 signal: controller.signal,
2 unmodified lines
12 // 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});16 const onStdoutData = iterateOnData({subprocessStdout, onStdoutChunk, controller, binary, preserveNewlines, isStream});17 return onStdoutData;18};1920const stopReadingOnExit = async (subprocess, controller) => {
12 unmodified lines
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}) {37const iterateOnData = async function * ({subprocessStdout, onStdoutChunk, controller, binary, preserveNewlines, isStream}) {38 const {39 encodeChunk = identityGenerator,40 encodeChunkFinal = noopGenerator,41 splitLines = identityGenerator,42 splitLinesFinal = noopGenerator,43 } = getTransforms({subprocessStdout, binary, preserveNewlines});43 } = getTransforms({subprocessStdout, binary, preserveNewlines, isStream});4445 try {46 for await (const [chunk] of onStdoutChunk) {47 yield * handleChunk(encodeChunk, splitLines, chunk);
6 unmodified lines
54 yield * handleFinalChunks(encodeChunkFinal, splitLines, splitLinesFinal);55 }56};5758const getTransforms = ({subprocessStdout, binary, preserveNewlines}) => {58const getTransforms = ({subprocessStdout, binary, preserveNewlines, isStream}) => {59 if (subprocessStdout.readableObjectMode) {60 return {};61 }62
2 unmodified lines
65 if (!binary) {66 return getTextTransforms(binary, preserveNewlines, writableObjectMode);67 }6869 return {};69 return isStream ? {} : getBinaryTransforms(writableObjectMode);70};7172const getTextTransforms = (binary, preserveNewlines, writableObjectMode) => {73 const encoding = 'utf8';
1 unmodified line
75 const {transform: splitLines, final: splitLinesFinal} = getSplitLinesGenerator({encoding, binary, preserveNewlines, writableObjectMode, state: {}});76 return {encodeChunk, encodeChunkFinal, splitLines, splitLinesFinal};77};7879const getBinaryTransforms = writableObjectMode => {80 const encoding = 'buffer';81 const {transform: encodeChunk} = getEncodingTransformGenerator(encoding, writableObjectMode, false);82 return {encodeChunk};83};8485const identityGenerator = function * (chunk) {86 yield chunk;87};8889const noopGenerator = function * () {};9091const handleChunk = function * (encodeChunk, splitLines, chunk) {86 for (const chunkString of encodeChunk(chunk)) {87 yield * splitLines(chunkString);92 for (const encodedChunk of encodeChunk(chunk)) {93 yield * splitLines(encodedChunk);94 }95};9697const handleFinalChunks = function * (encodeChunkFinal, splitLines, splitLinesFinal) {92 for (const chunkString of encodeChunkFinal()) {93 yield * splitLines(chunkString);98 for (const encodedChunk of encodeChunkFinal()) {99 yield * splitLines(encodedChunk);100 }101102 yield * splitLinesFinal();103};
modified:lib/convert/readable.js+1 added-1 removed
38 unmodified lines
39 : {readableEncoding, readableObjectMode: true, readableHighWaterMark: DEFAULT_OBJECT_HIGH_WATER_MARK};4041export const getReadableMethods = ({subprocessStdout, subprocess, binary, preserveNewlines}) => {42 const onStdoutDataDone = createDeferred();43 const onStdoutData = iterateOnStdout({subprocessStdout, subprocess, binary, preserveNewlines});43 const onStdoutData = iterateOnStdout({subprocessStdout, subprocess, binary, preserveNewlines, isStream: true});4445 return {46 read() {47 onRead(this, onStdoutData, onStdoutDataDone);
46 unmodified lines
modified:lib/async.js+1 added-1 removed
63 unmodified lines
64 cleanupOnExit(subprocess, options, controller);6566 subprocess.kill = subprocessKill.bind(undefined, {kill: subprocess.kill.bind(subprocess), subprocess, options, controller});67 subprocess.all = makeAllStream(subprocess, options);68 addConvertedStreams(subprocess);68 addConvertedStreams(subprocess, options);6970 const promise = handlePromise({subprocess, options, startTime, verboseInfo, stdioStreamsGroups, originalStreams, command, escapedCommand, controller});71 return {subprocess, promise};72};
34 unmodified lines
added:test/convert/iterable.js+154 added
1import test from 'ava';2import {execa} from '../../index.js';3import {setFixtureDir} from '../helpers/fixtures-dir.js';4import {foobarString} from '../helpers/input.js';5import {fullStdio, assertEpipe} from '../helpers/stdio.js';6import {7 arrayFromAsync,8 assertWritableAborted,9 assertReadableAborted,10 assertProcessNormalExit,11} from '../helpers/convert.js';12import {simpleFull, noNewlinesChunks} from '../helpers/lines.js';1314setFixtureDir();1516const partialArrayFromAsync = async (asyncIterable, lines = []) => {17 // eslint-disable-next-line no-unreachable-loop18 for await (const line of asyncIterable) {19 lines.push(line);20 break;21 }2223 return lines;24};2526const errorArrayFromAsync = async (t, cause, asyncIterable, lines = []) => {27 const {value} = await asyncIterable.next();28 lines.push(value);29 await asyncIterable.throw(cause);30};3132const throwsAsync = async (t, asyncIterable, arrayFromAsyncMethod) => {33 const lines = [];34 const error = await t.throwsAsync(arrayFromAsyncMethod(asyncIterable, lines));35 return {error, lines};36};3738const assertStdoutAbort = (t, subprocess, error, cause) => {39 assertProcessNormalExit(t, error, 1);40 assertEpipe(t, error.stderr);41 assertWritableAborted(t, subprocess.stdin);42 t.true(subprocess.stderr.readableEnded);4344 if (cause === undefined) {45 assertReadableAborted(t, subprocess.stdout);46 } else {47 t.is(subprocess.stdout.errored, cause);48 }49};5051const testSuccess = async (t, fdNumber, from, options = {}) => {52 const lines = await arrayFromAsync(execa('noop-fd.js', [`${fdNumber}`, simpleFull], options).iterable({from}));53 t.deepEqual(lines, noNewlinesChunks);54};5556test('Uses stdout by default', testSuccess, 1, undefined);57test('Can iterate successfully on stdout', testSuccess, 1, 'stdout');58test('Can iterate successfully on stderr', testSuccess, 2, 'stderr');59test('Can iterate successfully on stdio[*]', testSuccess, 3, 'fd3', fullStdio);6061test('Can iterate successfully on all', async t => {62 const lines = await arrayFromAsync(execa('noop-both.js', [simpleFull], {all: true}).iterable({from: 'all'}));63 t.deepEqual(lines, [...noNewlinesChunks, ...noNewlinesChunks]);64});6566test('Can iterate using Symbol.asyncIterator', async t => {67 const lines = await arrayFromAsync(execa('noop-fd.js', ['1', simpleFull]));68 t.deepEqual(lines, noNewlinesChunks);69});7071const assertMultipleCalls = async (t, iterable, iterableTwo) => {72 t.not(iterable, iterableTwo);73 const lines = await arrayFromAsync(iterable);74 const linesTwo = await arrayFromAsync(iterableTwo);75 t.deepEqual(lines, linesTwo);76 t.deepEqual(lines, noNewlinesChunks);77};7879test('Can be called multiple times', async t => {80 const subprocess = execa('noop-fd.js', ['1', simpleFull]);81 const iterable = subprocess.iterable();82 const iterableTwo = subprocess.iterable();83 await assertMultipleCalls(t, iterable, iterableTwo);84});8586test('Can be called on different file descriptors', async t => {87 const subprocess = execa('noop-both.js', [simpleFull]);88 const iterable = subprocess.iterable();89 const iterableTwo = subprocess.iterable({from: 'stderr'});90 await assertMultipleCalls(t, iterable, iterableTwo);91});9293test('Wait for the subprocess exit', async t => {94 const subprocess = execa('noop-delay.js', ['1', simpleFull]);95 const linesPromise = arrayFromAsync(subprocess);96 t.is(await Promise.race([linesPromise, subprocess]), await subprocess);97 t.deepEqual(await linesPromise, noNewlinesChunks);98});99100test('Wait for the subprocess exit on iterator.return()', async t => {101 const subprocess = execa('noop-delay.js', ['1', simpleFull]);102 const linesPromise = partialArrayFromAsync(subprocess);103 t.is(await Promise.race([linesPromise, subprocess]), await subprocess);104 t.deepEqual(await linesPromise, [noNewlinesChunks[0]]);105});106107test('Wait for the subprocess exit on iterator.throw()', async t => {108 const subprocess = execa('noop-delay.js', ['1', simpleFull]);109 const cause = new Error(foobarString);110 const lines = [];111 const linesPromise = t.throwsAsync(errorArrayFromAsync(t, cause, subprocess.iterable(), lines));112 t.is(await Promise.race([linesPromise, subprocess]), await subprocess);113 t.deepEqual(lines, [noNewlinesChunks[0]]);114});115116test('Abort stdout on iterator.return()', async t => {117 const subprocess = execa('noop-repeat.js', ['1', simpleFull]);118 const {error, lines} = await throwsAsync(t, subprocess, partialArrayFromAsync);119 t.deepEqual(lines, [noNewlinesChunks[0]]);120 assertStdoutAbort(t, subprocess, error);121 t.is(error, await t.throwsAsync(subprocess));122});123124test('Abort stdout on iterator.throw()', async t => {125 const subprocess = execa('noop-repeat.js', ['1', simpleFull]);126 const cause = new Error(foobarString);127 const {error, lines} = await throwsAsync(t, subprocess.iterable(), errorArrayFromAsync.bind(undefined, t, cause));128 t.deepEqual(lines, [noNewlinesChunks[0]]);129 assertStdoutAbort(t, subprocess, error);130 t.is(error, await t.throwsAsync(subprocess));131});132133test('Propagate subprocess failure', async t => {134 const subprocess = execa('noop-fail.js', ['1', simpleFull]);135 const {error, lines} = await throwsAsync(t, subprocess, arrayFromAsync);136 t.is(error, await t.throwsAsync(subprocess));137 t.deepEqual(lines, noNewlinesChunks);138});139140const testStdoutError = async (t, destroyStdout, isAbort, cause) => {141 const subprocess = execa('noop-repeat.js', ['1', simpleFull]);142 subprocess.stdout.once('data', () => {143 destroyStdout(subprocess.stdout, cause);144 });145146 const {error} = await throwsAsync(t, subprocess, arrayFromAsync);147 t.is(error.cause, cause);148 assertStdoutAbort(t, subprocess, error, isAbort ? undefined : cause);149 t.is(error, await t.throwsAsync(subprocess));150};151152test('Propagate stdout abort', testStdoutError, subprocessStdout => subprocessStdout.destroy(), true);153test('Propagate stdout error', testStdoutError, (subprocessStdout, cause) => subprocessStdout.destroy(cause), false, new Error(foobarString));154test('Propagate stdout "error" event', testStdoutError, (subprocessStdout, cause) => subprocessStdout.emit('error', cause), true, new Error(foobarString));
modified:test/convert/loop.js+52 added-20 removed
2 unmodified lines
3import test from 'ava';4import {setFixtureDir} from '../helpers/fixtures-dir.js';5import {6 assertStreamOutput,7 assertIterableChunks,8 assertStreamChunks,9 assertSubprocessOutput,10 getReadableSubprocess,11 getReadWriteSubprocess,12} from '../helpers/convert.js';13import {14 stringToUint8Arrays,15 simpleFull,16 simpleChunks,17 simpleChunksBuffer,18 simpleChunksUint8Array,19 simpleLines,20 noNewlinesFull,21 complexFull,22 singleComplexBuffer,23 singleComplexUint8Array,24 complexChunks,25 complexChunksEnd,26} from '../helpers/lines.js';27import {outputObjectGenerator, getOutputGenerator} from '../helpers/generator.js';
13 unmodified lines
41 subprocess.stdin.end(output);42 return subprocess;43};4445const assertChunks = async (t, streamOrIterable, expectedChunks, methodName) => {46 const assertMethod = methodName === 'iterable' ? assertIterableChunks : assertStreamChunks;47 await assertMethod(t, streamOrIterable, expectedChunks);48};4950// eslint-disable-next-line max-params42const testText = async (t, expectedChunks, methodName, binary, preserveNewlines) => {43 const subprocess = getSubprocess(methodName, complexFull);51const testText = async (t, expectedChunks, methodName, binary, preserveNewlines, isUint8Array) => {52 const options = isUint8Array ? {encoding: 'buffer'} : {};53 const subprocess = getSubprocess(methodName, complexFull, options);54 const stream = subprocess[methodName]({binary, preserveNewlines});5546 await assertStreamChunks(t, stream, expectedChunks);47 await assertSubprocessOutput(t, subprocess, complexFull);56 await assertChunks(t, stream, expectedChunks, methodName);57 await assertSubprocessOutput(t, subprocess, stringToUint8Arrays(complexFull, isUint8Array));58};5960test('.iterable() can use "binary: true"', testText, singleComplexUint8Array, 'iterable', true, undefined, false);61test('.iterable() can use "binary: undefined"', testText, complexChunks, 'iterable', undefined, undefined, false);62test('.iterable() can use "binary: undefined" + "encoding: buffer"', testText, singleComplexUint8Array, 'iterable', undefined, undefined, true);63test('.iterable() can use "binary: false"', testText, complexChunks, 'iterable', false, undefined, false);64test('.iterable() can use "binary: false" + "preserveNewlines: true"', testText, complexChunksEnd, 'iterable', false, true, false);65test('.iterable() can use "binary: false" + "preserveNewlines: false"', testText, complexChunks, 'iterable', false, false, false);66test('.readable() can use "binary: true"', testText, singleComplexBuffer, 'readable', true, undefined, false);50test('.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);67test('.readable() can use "binary: undefined"', testText, singleComplexBuffer, 'readable', undefined, undefined, false);68test('.readable() can use "binary: undefined" + "encoding: buffer"', testText, singleComplexBuffer, 'readable', undefined, undefined, true);69test('.readable() can use "binary: false"', testText, complexChunksEnd, 'readable', false, undefined, false);70test('.readable() can use "binary: false" + "preserveNewlines: true"', testText, complexChunksEnd, 'readable', false, true, false);71test('.readable() can use "binary: false" + "preserveNewlines: false"', testText, complexChunks, 'readable', false, false, false);72test('.duplex() can use "binary: true"', testText, singleComplexBuffer, 'duplex', true, undefined, false);73test('.duplex() can use "binary: undefined"', testText, singleComplexBuffer, 'duplex', undefined, undefined, false);74test('.duplex() can use "binary: undefined" + "encoding: "buffer"', testText, singleComplexBuffer, 'duplex', undefined, undefined, true);75test('.duplex() can use "binary: false"', testText, complexChunksEnd, 'duplex', false, undefined, false);76test('.duplex() can use "binary: false" + "preserveNewlines: true"', testText, complexChunksEnd, 'duplex', false, true, false);77test('.duplex() can use "binary: false" + "preserveNewlines: false"', testText, complexChunks, 'duplex', false, false, false);7879const testTextOutput = async (t, expectedOutput, methodName, preserveNewlines) => {80 const subprocess = getSubprocess(methodName, complexFull);81 const stream = subprocess[methodName]({binary: false, preserveNewlines});
20 unmodified lines
102 t.is(subprocess.stdout.readableObjectMode, initialObjectMode);103 t.is(subprocess.stdout.readableHighWaterMark, getDefaultHighWaterMark(initialObjectMode));104105 const stream = subprocess[methodName]({binary, preserveNewlines: true});106107 if (methodName !== 'iterable') {88 t.is(stream.readableEncoding, encoding);89 t.is(stream.readableObjectMode, finalObjectMode);90 t.is(stream.readableHighWaterMark, getDefaultHighWaterMark(finalObjectMode));108 t.is(stream.readableEncoding, encoding);109 t.is(stream.readableObjectMode, finalObjectMode);110 t.is(stream.readableHighWaterMark, getDefaultHighWaterMark(finalObjectMode));111 }112113 t.is(subprocess.stdout.readableEncoding, encoding);114 t.is(subprocess.stdout.readableObjectMode, initialObjectMode);115 t.is(subprocess.stdout.readableHighWaterMark, getDefaultHighWaterMark(initialObjectMode));11695 await assertStreamChunks(t, stream, expectedChunks);117 await assertChunks(t, stream, expectedChunks, methodName);118 await subprocess;119};120121test('.iterable() uses Buffers with "binary: true"', testObjectMode, simpleChunksUint8Array, 'iterable', null, false, false, true);122test('.iterable() uses strings with "binary: true" and .setEncoding("utf8")', testObjectMode, simpleChunks, 'iterable', 'utf8', false, false, true);123test('.iterable() uses strings with "binary: true" and "encoding: buffer"', testObjectMode, simpleChunks, 'iterable', 'utf8', false, false, true, {encoding: 'buffer'});124test('.iterable() uses strings in objectMode with "binary: true" and object transforms', testObjectMode, foobarObjectChunks, 'iterable', null, true, true, true, {stdout: outputObjectGenerator});125test('.iterable() uses strings in objectMode with "binary: false"', testObjectMode, simpleLines, 'iterable', null, false, true, false);126test('.iterable() uses strings in objectMode with "binary: false" and .setEncoding("utf8")', testObjectMode, simpleLines, 'iterable', 'utf8', false, true, false);127test('.iterable() uses strings in objectMode with "binary: false" and "encoding: buffer"', testObjectMode, simpleLines, 'iterable', 'utf8', false, true, false, {encoding: 'buffer'});128test('.iterable() uses strings in objectMode with "binary: false" and object transforms', testObjectMode, foobarObjectChunks, 'iterable', null, true, true, false, {stdout: outputObjectGenerator});129test('.readable() uses Buffers with "binary: true"', testObjectMode, simpleChunksBuffer, 'readable', null, false, false, true);130test('.readable() uses strings with "binary: true" and .setEncoding("utf8")', testObjectMode, simpleChunks, 'readable', 'utf8', false, false, true);131test('.readable() uses strings with "binary: true" and "encoding: buffer"', testObjectMode, simpleChunks, 'readable', 'utf8', false, false, true, {encoding: 'buffer'});132test('.readable() uses strings in objectMode with "binary: true" and object transforms', testObjectMode, foobarObjectChunks, 'readable', null, true, true, true, {stdout: outputObjectGenerator});
12 unmodified lines
145146const testObjectSplit = async (t, methodName) => {147 const subprocess = getSubprocess(methodName, foobarString, {stdout: getOutputGenerator(simpleFull, true)});148 const stream = subprocess[methodName]({binary: false});119 await assertStreamChunks(t, stream, [simpleFull]);149 await assertChunks(t, stream, [simpleFull], methodName);150 await subprocess;151};152153test('.iterable() "binary: false" does not split lines of strings produced by object transforms', testObjectSplit, 'iterable');154test('.readable() "binary: false" does not split lines of strings produced by object transforms', testObjectSplit, 'readable');155test('.duplex() "binary: false" does not split lines of strings produced by object transforms', testObjectSplit, 'duplex');156157const testMultibyteCharacters = async (t, methodName) => {158 const subprocess = getReadWriteSubprocess();159 const stream = subprocess[methodName]({binary: false});129 const assertPromise = assertStreamOutput(t, stream, `${multibyteChar}${brokenSymbol}`);160 const assertPromise = assertChunks(t, stream, [`${multibyteChar}${brokenSymbol}`], methodName);161 subprocess.stdin.write(multibyteUint8Array.slice(0, breakingLength));162 await once(subprocess.stdout, 'data');163 subprocess.stdin.end();164 await assertPromise;165};166167test('.iterable() "binary: false" handles partial multibyte characters', testMultibyteCharacters, 'iterable');168test('.readable() "binary: false" handles partial multibyte characters', testMultibyteCharacters, 'readable');169test('.duplex() "binary: false" handles partial multibyte characters', testMultibyteCharacters, 'duplex');
modified:test/fixtures/noop-delay.js+2 added-1 removed
3 unmodified lines
4import {getWriteStream} from '../helpers/fs.js';5import {foobarString} from '../helpers/input.js';67const fdNumber = Number(process.argv[2]);8const bytes = process.argv[3] || foobarString;8getWriteStream(fdNumber).write(foobarString);9getWriteStream(fdNumber).write(bytes);10await setTimeout(100);
modified:test/helpers/convert.js+12 added
2 unmodified lines
3import isPlainObj from 'is-plain-obj';4import {execa} from '../../index.js';5import {foobarString} from '../helpers/input.js';67export const arrayFromAsync = async (asyncIterable, lines = []) => {8 for await (const line of asyncIterable) {9 lines.push(line);10 }1112 return lines;13};1415export const finishedStream = stream => finished(stream, {cleanup: true});1617export const assertWritableAborted = (t, writable) => {18 t.false(writable.writableEnded);
15 unmodified lines
34export const assertStreamOutput = async (t, stream, expectedOutput = foobarString) => {35 t.is(await text(stream), expectedOutput);36};3738export const assertIterableChunks = async (t, asyncIterable, expectedChunks) => {39 t.deepEqual(await arrayFromAsync(asyncIterable), expectedChunks);40};4142export const assertStreamChunks = async (t, stream, expectedOutput) => {43 t.deepEqual(await stream.toArray(), expectedOutput);44};45
28 unmodified lines
modified:test/helpers/lines.js+19 added-15 removed
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'];143const textEncoder = new TextEncoder();4const textDecoder = new TextDecoder();56export const getEncoding = isUint8Array => isUint8Array ? 'buffer' : 'utf8';720export const stringsToUint8Arrays = (strings, isUint8Array) => isUint8Array21 ? strings.map(string => textEncoder.encode(string))22 : strings;8export const stringsToUint8Arrays = (strings, isUint8Array) => strings.map(string => stringToUint8Arrays(string, isUint8Array));910export const stringToUint8Arrays = (string, isUint8Array) => isUint8Array11 ? textEncoder.encode(string)12 : string;1314export const stringsToBuffers = (strings, isUint8Array) => isUint8Array15 ? strings.map(string => Buffer.from(string))16 : strings;17
3 unmodified lines
2122const serializeResultItem = (resultItem, isUint8Array) => isUint8Array23 ? textDecoder.decode(resultItem)24 : resultItem;2526export const simpleFull = 'aaa\nbbb\nccc';27export const simpleChunks = [simpleFull];28export const simpleChunksBuffer = [Buffer.from(simpleFull)];29export const simpleChunksUint8Array = stringsToUint8Arrays(simpleChunks, true);30export const simpleLines = ['aaa\n', 'bbb\n', 'ccc'];31export const simpleFullEndLines = ['aaa\n', 'bbb\n', 'ccc\n'];32export const noNewlinesFull = 'aaabbbccc';33export const noNewlinesChunks = ['aaa', 'bbb', 'ccc'];34export const complexFull = '\naaa\r\nbbb\n\nccc';35export const singleComplexBuffer = [Buffer.from(complexFull)];36export const singleComplexUint8Array = stringsToUint8Arrays([complexFull], true);37export const complexChunksEnd = ['\n', 'aaa\r\n', 'bbb\n', '\n', 'ccc'];38export const complexChunks = ['', 'aaa', 'bbb', '', 'ccc'];
modified:test/helpers/stdio.js+9 added-1 removed
1import process from 'node:process';1import process, {platform} from 'node:process';2import {noopReadable} from './stream.js';34export const identity = value => value;5
12 unmodified lines
1819export const STANDARD_STREAMS = [process.stdin, process.stdout, process.stderr];2021export const prematureClose = {code: 'ERR_STREAM_PREMATURE_CLOSE'};2223const isWindows = platform === 'win32';2425export const assertEpipe = (t, stderr, fdNumber = 1) => {26 if (fdNumber === 1 && !isWindows) {27 t.true(stderr.includes('EPIPE'));28 }29};
modified:test/pipe/validate.js+157 added
73 unmodified lines
74 });75 t.true(error.message.includes(getMessage(message)));76};7778const testIterable = async (t, {79 message,80 sourceOptions = {},81 getSource = () => execa('empty.js', sourceOptions),82 from,83}) => {84 const error = t.throws(() => {85 getSource().iterable({from});86 });87 t.true(error.message.includes(getMessage(message)));88};8990test('Must set "all" option to "true" to use .pipe("all")', testPipeError, {91 from: 'all',92 message: '"all" option must be true',93});94test('Must set "all" option to "true" to use .duplex("all")', testNodeStream, {95 from: 'all',96 message: '"all" option must be true',97});98test('Must set "all" option to "true" to use .iterable("all")', testIterable, {99 from: 'all',100 message: '"all" option must be true',101});102test('.pipe() cannot pipe to non-subprocesses', testPipeError, {103 getDestination: () => new PassThrough(),104 message: 'an Execa subprocess',105});
8 unmodified lines
114test('.duplex() "from" option cannot be "stdin"', testNodeStream, {115 from: 'stdin',116 message: '"from" must not be',117});118test('.iterable() "from" option cannot be "stdin"', testIterable, {119 from: 'stdin',120 message: '"from" must not be',121});122test('$.pipe() "from" option cannot be "stdin"', testPipeError, {123 from: 'stdin',124 isScript: true,125 message: '"from" must not be',
18 unmodified lines
144test('.duplex() "from" option cannot be any string', testNodeStream, {145 from: 'other',146 message: 'must be "stdout", "stderr", "all"',147});148test('.iterable() "from" option cannot be any string', testIterable, {149 from: 'other',150 message: 'must be "stdout", "stderr", "all"',151});152test('.pipe() "to" option cannot be any string', testPipeError, {153 to: 'other',154 message: 'must be "stdin"',155});
8 unmodified lines
164test('.duplex() "from" option cannot be a number without "fd"', testNodeStream, {165 from: '1',166 message: 'must be "stdout", "stderr", "all"',167});168test('.iterable() "from" option cannot be a number without "fd"', testIterable, {169 from: '1',170 message: 'must be "stdout", "stderr", "all"',171});172test('.pipe() "to" option cannot be a number without "fd"', testPipeError, {173 to: '0',174 message: 'must be "stdin"',175});
8 unmodified lines
184test('.duplex() "from" option cannot be just "fd"', testNodeStream, {185 from: 'fd',186 message: 'must be "stdout", "stderr", "all"',187});188test('.iterable() "from" option cannot be just "fd"', testIterable, {189 from: 'fd',190 message: 'must be "stdout", "stderr", "all"',191});192test('.pipe() "to" option cannot be just "fd"', testPipeError, {193 to: 'fd',194 message: 'must be "stdin"',195});
8 unmodified lines
204test('.duplex() "from" option cannot be a float', testNodeStream, {205 from: 'fd1.5',206 message: 'must be "stdout", "stderr", "all"',207});208test('.iterable() "from" option cannot be a float', testIterable, {209 from: 'fd1.5',210 message: 'must be "stdout", "stderr", "all"',211});212test('.pipe() "to" option cannot be a float', testPipeError, {213 to: 'fd1.5',214 message: 'must be "stdin"',215});
8 unmodified lines
224test('.duplex() "from" option cannot be a negative number', testNodeStream, {225 from: 'fd-1',226 message: 'must be "stdout", "stderr", "all"',227});228test('.iterable() "from" option cannot be a negative number', testIterable, {229 from: 'fd-1',230 message: 'must be "stdout", "stderr", "all"',231});232test('.pipe() "to" option cannot be a negative number', testPipeError, {233 to: 'fd-1',234 message: 'must be "stdin"',235});
8 unmodified lines
244test('.duplex() "from" cannot be a non-existing file descriptor', testNodeStream, {245 from: 'fd3',246 message: 'file descriptor does not exist',247});248test('.iterable() "from" cannot be a non-existing file descriptor', testIterable, {249 from: 'fd3',250 message: 'file descriptor does not exist',251});252test('.pipe() "to" option cannot be a non-existing file descriptor', testPipeError, {253 to: 'fd3',254 message: 'file descriptor does not exist',255});
10 unmodified lines
266 sourceOptions: getStdio(3, new Uint8Array()),267 from: 'fd3',268 message: 'must be a readable stream',269});270test('.iterable() "from" option cannot be an input file descriptor', testIterable, {271 sourceOptions: getStdio(3, new Uint8Array()),272 from: 'fd3',273 message: 'must be a readable stream',274});275test('.pipe() "to" option cannot be an output file descriptor', testPipeError, {276 destinationOptions: fullStdio,277 to: 'fd3',278 message: 'must be a writable stream',
20 unmodified lines
299test('Cannot set "stdout" option to "ignore" to use .duplex()', testNodeStream, {300 sourceOptions: {stdout: 'ignore'},301 message: ['stdout', '\'ignore\''],302});303test('Cannot set "stdout" option to "ignore" to use .iterable()', testIterable, {304 sourceOptions: {stdout: 'ignore'},305 message: ['stdout', '\'ignore\''],306});307test('Cannot set "stdin" option to "ignore" to use .pipe()', testPipeError, {308 destinationOptions: {stdin: 'ignore'},309 message: ['stdin', '\'ignore\''],310});
11 unmodified lines
322 sourceOptions: {stdout: 'ignore'},323 from: 'fd1',324 message: ['stdout', '\'ignore\''],325});326test('Cannot set "stdout" option to "ignore" to use .iterable(1)', testIterable, {327 sourceOptions: {stdout: 'ignore'},328 from: 'fd1',329 message: ['stdout', '\'ignore\''],330});331test('Cannot set "stdin" option to "ignore" to use .pipe(0)', testPipeError, {332 destinationOptions: {stdin: 'ignore'},333 message: ['stdin', '\'ignore\''],334 to: 'fd0',
12 unmodified lines
347 sourceOptions: {stdout: 'ignore'},348 from: 'stdout',349 message: ['stdout', '\'ignore\''],350});351test('Cannot set "stdout" option to "ignore" to use .iterable("stdout")', testIterable, {352 sourceOptions: {stdout: 'ignore'},353 from: 'stdout',354 message: ['stdout', '\'ignore\''],355});356test('Cannot set "stdin" option to "ignore" to use .pipe("stdin")', testPipeError, {357 destinationOptions: {stdin: 'ignore'},358 message: ['stdin', '\'ignore\''],359 to: 'stdin',
10 unmodified lines
370test('Cannot set "stdout" + "stderr" option to "ignore" to use .duplex()', testNodeStream, {371 sourceOptions: {stdout: 'ignore', stderr: 'ignore'},372 message: ['stdout', '\'ignore\''],373});374test('Cannot set "stdout" + "stderr" option to "ignore" to use .iterable()', testIterable, {375 sourceOptions: {stdout: 'ignore', stderr: 'ignore'},376 message: ['stdout', '\'ignore\''],377});378test('Cannot set "stdout" + "stderr" option to "ignore" to use .pipe(1)', testPipeError, {379 sourceOptions: {stdout: 'ignore', stderr: 'ignore'},380 from: 'fd1',381 message: ['stdout', '\'ignore\''],
2 unmodified lines
384 sourceOptions: {stdout: 'ignore', stderr: 'ignore'},385 from: 'fd1',386 message: ['stdout', '\'ignore\''],387});388test('Cannot set "stdout" + "stderr" option to "ignore" to use .iterable(1)', testIterable, {389 sourceOptions: {stdout: 'ignore', stderr: 'ignore'},390 from: 'fd1',391 message: ['stdout', '\'ignore\''],392});393test('Cannot set "stdout" + "stderr" option to "ignore" to use .pipe("stdout")', testPipeError, {394 sourceOptions: {stdout: 'ignore', stderr: 'ignore'},395 from: 'stdout',396 message: ['stdout', '\'ignore\''],
2 unmodified lines
399 sourceOptions: {stdout: 'ignore', stderr: 'ignore'},400 from: 'stdout',401 message: ['stdout', '\'ignore\''],402});403test('Cannot set "stdout" + "stderr" option to "ignore" to use .iterable("stdout")', testIterable, {404 sourceOptions: {stdout: 'ignore', stderr: 'ignore'},405 from: 'stdout',406 message: ['stdout', '\'ignore\''],407});408test('Cannot set "stdio[1]" option to "ignore" to use .pipe()', testPipeError, {409 sourceOptions: {stdio: ['pipe', 'ignore', 'pipe']},410 message: ['stdio[1]', '\'ignore\''],411});412test('Cannot set "stdio[1]" option to "ignore" to use .duplex()', testNodeStream, {413 sourceOptions: {stdio: ['pipe', 'ignore', 'pipe']},414 message: ['stdio[1]', '\'ignore\''],415});416test('Cannot set "stdio[1]" option to "ignore" to use .iterable()', testIterable, {417 sourceOptions: {stdio: ['pipe', 'ignore', 'pipe']},418 message: ['stdio[1]', '\'ignore\''],419});420test('Cannot set "stdio[0]" option to "ignore" to use .pipe()', testPipeError, {421 destinationOptions: {stdio: ['ignore', 'pipe', 'pipe']},422 message: ['stdio[0]', '\'ignore\''],423});
11 unmodified lines
435 sourceOptions: {stdio: ['pipe', 'ignore', 'pipe']},436 from: 'fd1',437 message: ['stdio[1]', '\'ignore\''],438});439test('Cannot set "stdio[1]" option to "ignore" to use .iterable(1)', testIterable, {440 sourceOptions: {stdio: ['pipe', 'ignore', 'pipe']},441 from: 'fd1',442 message: ['stdio[1]', '\'ignore\''],443});444test('Cannot set "stdio[0]" option to "ignore" to use .pipe(0)', testPipeError, {445 destinationOptions: {stdio: ['ignore', 'pipe', 'pipe']},446 message: ['stdio[0]', '\'ignore\''],447 to: 'fd0',
12 unmodified lines
460 sourceOptions: {stdio: ['pipe', 'ignore', 'pipe']},461 from: 'stdout',462 message: ['stdio[1]', '\'ignore\''],463});464test('Cannot set "stdio[1]" option to "ignore" to use .iterable("stdout")', testIterable, {465 sourceOptions: {stdio: ['pipe', 'ignore', 'pipe']},466 from: 'stdout',467 message: ['stdio[1]', '\'ignore\''],468});469test('Cannot set "stdio[0]" option to "ignore" to use .pipe("stdin")', testPipeError, {470 destinationOptions: {stdio: ['ignore', 'pipe', 'pipe']},471 message: ['stdio[0]', '\'ignore\''],472 to: 'stdin',
12 unmodified lines
485 sourceOptions: {stderr: 'ignore'},486 from: 'fd2',487 message: ['stderr', '\'ignore\''],488});489test('Cannot set "stderr" option to "ignore" to use .iterable(2)', testIterable, {490 sourceOptions: {stderr: 'ignore'},491 from: 'fd2',492 message: ['stderr', '\'ignore\''],493});494test('Cannot set "stderr" option to "ignore" to use .pipe("stderr")', testPipeError, {495 sourceOptions: {stderr: 'ignore'},496 from: 'stderr',497 message: ['stderr', '\'ignore\''],
2 unmodified lines
500 sourceOptions: {stderr: 'ignore'},501 from: 'stderr',502 message: ['stderr', '\'ignore\''],503});504test('Cannot set "stderr" option to "ignore" to use .iterable("stderr")', testIterable, {505 sourceOptions: {stderr: 'ignore'},506 from: 'stderr',507 message: ['stderr', '\'ignore\''],508});509test('Cannot set "stdout" + "stderr" option to "ignore" to use .pipe(2)', testPipeError, {510 sourceOptions: {stdout: 'ignore', stderr: 'ignore'},511 from: 'fd2',512 message: ['stderr', '\'ignore\''],
2 unmodified lines
515 sourceOptions: {stdout: 'ignore', stderr: 'ignore'},516 from: 'fd2',517 message: ['stderr', '\'ignore\''],518});519test('Cannot set "stdout" + "stderr" option to "ignore" to use .iterable(2)', testIterable, {520 sourceOptions: {stdout: 'ignore', stderr: 'ignore'},521 from: 'fd2',522 message: ['stderr', '\'ignore\''],523});524test('Cannot set "stdout" + "stderr" option to "ignore" to use .pipe("stderr")', testPipeError, {525 sourceOptions: {stdout: 'ignore', stderr: 'ignore'},526 from: 'stderr',527 message: ['stderr', '\'ignore\''],
2 unmodified lines
530 sourceOptions: {stdout: 'ignore', stderr: 'ignore'},531 from: 'stderr',532 message: ['stderr', '\'ignore\''],533});534test('Cannot set "stdout" + "stderr" option to "ignore" to use .iterable("stderr")', testIterable, {535 sourceOptions: {stdout: 'ignore', stderr: 'ignore'},536 from: 'stderr',537 message: ['stderr', '\'ignore\''],538});539test('Cannot set "stdio[2]" option to "ignore" to use .pipe(2)', testPipeError, {540 sourceOptions: {stdio: ['pipe', 'pipe', 'ignore']},541 from: 'fd2',542 message: ['stdio[2]', '\'ignore\''],
2 unmodified lines
545 sourceOptions: {stdio: ['pipe', 'pipe', 'ignore']},546 from: 'fd2',547 message: ['stdio[2]', '\'ignore\''],548});549test('Cannot set "stdio[2]" option to "ignore" to use .iterable(2)', testIterable, {550 sourceOptions: {stdio: ['pipe', 'pipe', 'ignore']},551 from: 'fd2',552 message: ['stdio[2]', '\'ignore\''],553});554test('Cannot set "stdio[2]" option to "ignore" to use .pipe("stderr")', testPipeError, {555 sourceOptions: {stdio: ['pipe', 'pipe', 'ignore']},556 from: 'stderr',557 message: ['stdio[2]', '\'ignore\''],
2 unmodified lines
560 sourceOptions: {stdio: ['pipe', 'pipe', 'ignore']},561 from: 'stderr',562 message: ['stdio[2]', '\'ignore\''],563});564test('Cannot set "stdio[2]" option to "ignore" to use .iterable("stderr")', testIterable, {565 sourceOptions: {stdio: ['pipe', 'pipe', 'ignore']},566 from: 'stderr',567 message: ['stdio[2]', '\'ignore\''],568});569test('Cannot set "stdio[3]" option to "ignore" to use .pipe(3)', testPipeError, {570 sourceOptions: getStdio(3, 'ignore'),571 from: 'fd3',572 message: ['stdio[3]', '\'ignore\''],
2 unmodified lines
575 sourceOptions: getStdio(3, 'ignore'),576 from: 'fd3',577 message: ['stdio[3]', '\'ignore\''],578});579test('Cannot set "stdio[3]" option to "ignore" to use .iterable(3)', testIterable, {580 sourceOptions: getStdio(3, 'ignore'),581 from: 'fd3',582 message: ['stdio[3]', '\'ignore\''],583});584test('Cannot set "stdout" + "stderr" option to "ignore" to use .pipe("all")', testPipeError, {585 sourceOptions: {stdout: 'ignore', stderr: 'ignore', all: true},586 from: 'all',587 message: ['stdout', '\'ignore\''],
2 unmodified lines
590 sourceOptions: {stdout: 'ignore', stderr: 'ignore', all: true},591 from: 'all',592 message: ['stdout', '\'ignore\''],593});594test('Cannot set "stdout" + "stderr" option to "ignore" to use .iterable("all")', testIterable, {595 sourceOptions: {stdout: 'ignore', stderr: 'ignore', all: true},596 from: 'all',597 message: ['stdout', '\'ignore\''],598});599test('Cannot set "stdio[1]" + "stdio[2]" option to "ignore" to use .pipe("all")', testPipeError, {600 sourceOptions: {stdio: ['pipe', 'ignore', 'ignore'], all: true},601 from: 'all',602 message: ['stdio[1]', '\'ignore\''],
2 unmodified lines
605 sourceOptions: {stdio: ['pipe', 'ignore', 'ignore'], all: true},606 from: 'all',607 message: ['stdio[1]', '\'ignore\''],608});609test('Cannot set "stdio[1]" + "stdio[2]" option to "ignore" to use .iterable("all")', testIterable, {610 sourceOptions: {stdio: ['pipe', 'ignore', 'ignore'], all: true},611 from: 'all',612 message: ['stdio[1]', '\'ignore\''],613});614test('Cannot set "stdout" option to "inherit" to use .pipe()', testPipeError, {615 sourceOptions: {stdout: 'inherit'},616 message: ['stdout', '\'inherit\''],617});618test('Cannot set "stdout" option to "inherit" to use .duplex()', testNodeStream, {619 sourceOptions: {stdout: 'inherit'},620 message: ['stdout', '\'inherit\''],621});622test('Cannot set "stdout" option to "inherit" to use .iterable()', testIterable, {623 sourceOptions: {stdout: 'inherit'},624 message: ['stdout', '\'inherit\''],625});626test('Cannot set "stdin" option to "inherit" to use .pipe()', testPipeError, {627 destinationOptions: {stdin: 'inherit'},628 message: ['stdin', '\'inherit\''],629});
9 unmodified lines
639test('Cannot set "stdout" option to "ipc" to use .duplex()', testNodeStream, {640 sourceOptions: {stdout: 'ipc'},641 message: ['stdout', '\'ipc\''],642});643test('Cannot set "stdout" option to "ipc" to use .iterable()', testIterable, {644 sourceOptions: {stdout: 'ipc'},645 message: ['stdout', '\'ipc\''],646});647test('Cannot set "stdin" option to "ipc" to use .pipe()', testPipeError, {648 destinationOptions: {stdin: 'ipc'},649 message: ['stdin', '\'ipc\''],650});
9 unmodified lines
660test('Cannot set "stdout" option to file descriptors to use .duplex()', testNodeStream, {661 sourceOptions: {stdout: 1},662 message: ['stdout', '1'],663});664test('Cannot set "stdout" option to file descriptors to use .iterable()', testIterable, {665 sourceOptions: {stdout: 1},666 message: ['stdout', '1'],667});668test('Cannot set "stdin" option to file descriptors to use .pipe()', testPipeError, {669 destinationOptions: {stdin: 0},670 message: ['stdin', '0'],671});
9 unmodified lines
681test('Cannot set "stdout" option to Node.js streams to use .duplex()', testNodeStream, {682 sourceOptions: {stdout: process.stdout},683 message: ['stdout', 'Stream'],684});685test('Cannot set "stdout" option to Node.js streams to use .iterable()', testIterable, {686 sourceOptions: {stdout: process.stdout},687 message: ['stdout', 'Stream'],688});689test('Cannot set "stdin" option to Node.js streams to use .pipe()', testPipeError, {690 destinationOptions: {stdin: process.stdin},691 message: ['stdin', 'Stream'],692});
11 unmodified lines
704 sourceOptions: getStdio(3, process.stdout),705 message: ['stdio[3]', 'Stream'],706 from: 'fd3',707});708test('Cannot set "stdio[3]" option to Node.js Writable streams to use .iterable()', testIterable, {709 sourceOptions: getStdio(3, process.stdout),710 message: ['stdio[3]', 'Stream'],711 from: 'fd3',712});713test('Cannot set "stdio[3]" option to Node.js Readable streams to use .pipe()', testPipeError, {714 destinationOptions: getStdio(3, process.stdin),715 message: ['stdio[3]', 'Stream'],716 to: 'fd3',
67 unmodified lines
modified:test/stream/subprocess.js+2 added-7 removed
1import {platform} from 'node:process';1import {setTimeout} from 'node:timers/promises';2import test from 'ava';3import {execa} from '../../index.js';4import {setFixtureDir} from '../helpers/fixtures-dir.js';6import {fullStdio, getStdio, prematureClose} from '../helpers/stdio.js';5import {fullStdio, getStdio, prematureClose, assertEpipe} from '../helpers/stdio.js';6import {infiniteGenerator} from '../helpers/generator.js';78setFixtureDir();911const isWindows = platform === 'win32';1210const getStreamInputSubprocess = fdNumber => execa('stdin-fd.js', [`${fdNumber}`], fdNumber === 311 ? getStdio(3, [new Uint8Array(), infiniteGenerator])12 : {});13const getStreamOutputSubprocess = fdNumber => execa('noop-repeat.js', [`${fdNumber}`], fdNumber === 3 ? fullStdio : {});
13 unmodified lines
27 t.is(signal, undefined);28 t.false(isTerminated);29 t.true(failed);3034 if (fdNumber === 1 && !isWindows) {35 t.true(stderr.includes('EPIPE'));36 }31 assertEpipe(t, stderr, fdNumber);32};3334const testStreamInputAbort = async (t, fdNumber) => {35 const subprocess = getStreamInputSubprocess(fdNumber);
82 unmodified lines
modified:test/stream/wait.js+2 added-7 removed
1import {platform} from 'node:process';1import {setImmediate} from 'node:timers/promises';2import test from 'ava';3import {execa} from '../../index.js';4import {setFixtureDir} from '../helpers/fixtures-dir.js';6import {getStdio, prematureClose} from '../helpers/stdio.js';5import {getStdio, prematureClose, assertEpipe} from '../helpers/stdio.js';6import {foobarString} from '../helpers/input.js';7import {noopGenerator} from '../helpers/generator.js';8import {noopReadable, noopWritable, noopDuplex} from '../helpers/stream.js';910setFixtureDir();1113const isWindows = platform === 'win32';1412const noop = () => {};1314const endOptionStream = ({stream}) => {15 stream.end();
107 unmodified lines
123 const {exitCode, stdio, stderr} = await t.throwsAsync(subprocess);124 t.is(exitCode, 1);125 t.is(stdio[fdNumber], '');126 t.true(stream.destroyed);130 if (fdNumber !== 2 && !isWindows) {131 t.true(stderr.includes('EPIPE'));132 }127 assertEpipe(t, stderr, fdNumber);128};129130test('Throws EPIPE when stdout option ends with more writes', testStreamEpipeFail, endOptionStream, noopWritable(), 1, false);131test('Throws EPIPE when stdout option aborts with more writes', testStreamEpipeFail, destroyOptionStream, noopWritable(), 1, false);
80 unmodified lines
modified:index.d.ts+31 added-6 removed
989 unmodified lines
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).994 If `true`, the stream iterates over arbitrary chunks of data. Each line is an `Uint8Array` (with `.iterable()`) or a [`Buffer`](https://nodejs.org/api/buffer.html#class-buffer) (otherwise).995996 @default true996 @default `false` with `.iterable()` and `encoding: 'buffer'`, `true` otherwise997 */998 readonly binary?: boolean;9991000 /**1001 If both this option and the `binary` option is `false`, newlines are stripped from each line.10021003 @default true1003 @default `false` with `.iterable()`, `true` otherwise1004 */1005 readonly preserveNewlines?: boolean;1006};1007
7 unmodified lines
1015};10161017type DuplexOptions = ReadableOptions & WritableOptions;10181019type SubprocessAsyncIterable<1020 BinaryOption extends boolean | undefined,1021 EncodingOption extends Options['encoding'],1022> = AsyncIterableIterator<1023BinaryOption extends true1024 ? Uint8Array1025 : BinaryOption extends false1026 ? string1027 : EncodingOption extends 'buffer'1028 ? Uint8Array1029 : string1030>;10311032export type ExecaResultPromise<OptionsType extends Options = Options> = {1033 stdin: StreamUnlessIgnored<'0', OptionsType>;10341035 stdout: StreamUnlessIgnored<'1', OptionsType>;
25 unmodified lines
1061 kill(signal: Parameters<ChildProcess['kill']>[0], error?: Error): ReturnType<ChildProcess['kill']>;1062 kill(error?: Error): ReturnType<ChildProcess['kill']>;10631064 /**1065 Subprocesses are [async iterables](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol/asyncIterator). They iterate over each output line.10661067 The iteration waits for the subprocess to end. It throws if the subprocess fails. This means you do not need to `await` the subprocess' promise.1068 */1069 [Symbol.asyncIterator](): SubprocessAsyncIterable<undefined, OptionsType['encoding']>;10701071 /**1072 Same as `subprocess[Symbol.asyncIterator]` except options can be provided.1073 */1074 iterable<IterableOptions extends ReadableOptions = {}>(readableOptions?: IterableOptions): SubprocessAsyncIterable<IterableOptions['binary'], OptionsType['encoding']>;10751076 /**1077 Converts the subprocess to a readable stream.10781079 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.10801056 Before using this method, please first consider the `stdin`/`stdout`/`stderr`/`stdio` options or the `subprocess.pipe()` method.1081 Before using this method, please first consider the `stdin`/`stdout`/`stderr`/`stdio` options, `subprocess.pipe()` or `subprocess.iterable()`.1082 */1083 readable(readableOptions?: ReadableOptions): Readable;10841085 /**1086 Converts the subprocess to a writable stream.10871088 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.10891065 Before using this method, please first consider the `stdin`/`stdout`/`stderr`/`stdio` options or the `subprocess.pipe()` method.1090 Before using this method, please first consider the `stdin`/`stdout`/`stderr`/`stdio` options or `subprocess.pipe()`.1091 */1092 writable(writableOptions?: WritableOptions): Writable;10931094 /**1095 Converts the subprocess to a duplex stream.10961097 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.10981074 Before using this method, please first consider the `stdin`/`stdout`/`stderr`/`stdio` options or the `subprocess.pipe()` method.1099 Before using this method, please first consider the `stdin`/`stdout`/`stderr`/`stdio` options, `subprocess.pipe()` or `subprocess.iterable()`.1100 */1101 duplex(duplexOptions?: DuplexOptions): Duplex;1102} & PipableSubprocess;1103
477 unmodified lines
modified:index.test-d.ts+67 added
266 unmodified lines
267 expectType<string>(scriptShortcutPipeResult.stdout);268 const ignoreShortcutScriptPipeResult = await scriptPromise.pipe('stdin', {stdout: 'ignore'});269 expectType<undefined>(ignoreShortcutScriptPipeResult.stdout);270271 const asyncIteration = async () => {272 for await (const line of scriptPromise) {273 expectType<string>(line);274 }275276 for await (const line of scriptPromise.iterable()) {277 expectType<string>(line);278 }279280 for await (const line of scriptPromise.iterable({binary: false})) {281 expectType<string>(line);282 }283284 for await (const line of scriptPromise.iterable({binary: true})) {285 expectType<Uint8Array>(line);286 }287288 for await (const line of scriptPromise.iterable({} as {binary: boolean})) {289 expectType<string | Uint8Array>(line);290 }291292 for await (const line of execaBufferPromise) {293 expectType<Uint8Array>(line);294 }295296 for await (const line of execaBufferPromise.iterable()) {297 expectType<Uint8Array>(line);298 }299300 for await (const line of execaBufferPromise.iterable({binary: false})) {301 expectType<string>(line);302 }303304 for await (const line of execaBufferPromise.iterable({binary: true})) {305 expectType<Uint8Array>(line);306 }307308 for await (const line of execaBufferPromise.iterable({} as {binary: boolean})) {309 expectType<string | Uint8Array>(line);310 }311 };312313 await asyncIteration();314 expectAssignable<AsyncIterable<string>>(scriptPromise.iterable());315 expectAssignable<AsyncIterable<string>>(scriptPromise.iterable({binary: false}));316 expectAssignable<AsyncIterable<Uint8Array>>(scriptPromise.iterable({binary: true}));317 expectAssignable<AsyncIterable<string | Uint8Array>>(scriptPromise.iterable({} as {binary: boolean}));318 expectAssignable<AsyncIterable<Uint8Array>>(execaBufferPromise.iterable());319 expectAssignable<AsyncIterable<string>>(execaBufferPromise.iterable({binary: false}));320 expectAssignable<AsyncIterable<Uint8Array>>(execaBufferPromise.iterable({binary: true}));321 expectAssignable<AsyncIterable<string | Uint8Array>>(execaBufferPromise.iterable({} as {binary: boolean}));322323 expectType<Readable>(scriptPromise.readable());324 expectType<Writable>(scriptPromise.writable());325 expectType<Duplex>(scriptPromise.duplex());326327 scriptPromise.iterable({});328 scriptPromise.iterable({from: 'stdout'});329 scriptPromise.iterable({from: 'stderr'});330 scriptPromise.iterable({from: 'all'});331 scriptPromise.iterable({from: 'fd3'});332 scriptPromise.iterable({binary: false});333 scriptPromise.iterable({preserveNewlines: false});334 expectError(scriptPromise.iterable('stdout'));335 expectError(scriptPromise.iterable({from: 'stdin'}));336 expectError(scriptPromise.iterable({from: 'fd'}));337 expectError(scriptPromise.iterable({from: 'fdNotANumber'}));338 expectError(scriptPromise.iterable({binary: 'false'}));339 expectError(scriptPromise.iterable({preserveNewlines: 'false'}));340 expectError(scriptPromise.iterable({to: 'stdin'}));341 expectError(scriptPromise.iterable({other: 'stdout'}));342 scriptPromise.readable({});343 scriptPromise.readable({from: 'stdout'});344 scriptPromise.readable({from: 'stderr'});345 scriptPromise.readable({from: 'all'});
1394 unmodified lines
modified:readme.md+35 added-7 removed
206 unmodified lines
207console.log(pipedFrom[0]); // Result of `sort`208console.log(pipedFrom[0].pipedFrom[0]); // Result of `npm run build`209```210211#### Iterate over output lines212213```js214import {execa} from 'execa';215216for await (const line of execa('npm', ['run', 'build'])) {217 if (line.includes('ERROR')) {218 console.log(line);219 }220}221```222223### Handling Errors224225```js226import {execa} from 'execa';
222 unmodified lines
449When 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).450451[More info.](https://nodejs.org/api/child_process.html#subprocesskillsignal)452453#### [Symbol.asyncIterator]()454455_Returns_: `AsyncIterable`456457Subprocesses are [async iterables](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol/asyncIterator). They iterate over each output line.458459The iteration waits for the subprocess to end. It throws if the subprocess [fails](#subprocessresult). This means you do not need to `await` the subprocess' [promise](#subprocess).460461#### iterable(readableOptions?)462463`readableOptions`: [`ReadableOptions`](#readableoptions)\464_Returns_: `AsyncIterable`465466Same as [`subprocess[Symbol.asyncIterator]`](#symbolasynciterator) except [options](#readableoptions) can be provided.467468#### readable(readableOptions?)469470`readableOptions`: [`ReadableOptions`](#readableoptions)\471_Returns_: [`Readable`](https://nodejs.org/api/stream.html#class-streamreadable) Node.js stream
1 unmodified line
473Converts the subprocess to a readable stream.474475Unlike [`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.476450Before 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.477Before using this method, please first consider the [`stdin`](#stdin)/[`stdout`](#stdout-1)/[`stderr`](#stderr-1)/[`stdio`](#stdio-1) options, [`subprocess.pipe()`](#pipefile-arguments-options) or [`subprocess.iterable()`](#iterablereadableoptions).478479#### writable(writableOptions?)480481`writableOptions`: [`WritableOptions`](#writableoptions)\
2 unmodified lines
484Converts the subprocess to a writable stream.485486Unlike [`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.487461Before 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.488Before using this method, please first consider the [`stdin`](#stdin)/[`stdout`](#stdout-1)/[`stderr`](#stderr-1)/[`stdio`](#stdio-1) options or [`subprocess.pipe()`](#pipefile-arguments-options).489490#### duplex(duplexOptions?)491492`duplexOptions`: [`ReadableOptions | WritableOptions`](#readableoptions)\
2 unmodified lines
495Converts the subprocess to a duplex stream.496497The 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.498472Before 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.499Before using this method, please first consider the [`stdin`](#stdin)/[`stdout`](#stdout-1)/[`stderr`](#stderr-1)/[`stdio`](#stdio-1) options, [`subprocess.pipe()`](#pipefile-arguments-options) or [`subprocess.iterable()`](#iterablereadableoptions).500501##### readableOptions502503Type: `object`
8 unmodified lines
512`"all"` reads both `stdout` and `stderr`. This requires the [`all` option](#all-2) to be `true`.513514##### readableOptions.binary515489Type: `boolean`\490Default: `true`516Type: `boolean`517518If `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).519494If `true`, the stream iterates over arbitrary chunks of data. Each line is a [`Buffer`](https://nodejs.org/api/buffer.html#class-buffer).520If `true`, the stream iterates over arbitrary chunks of data. Each line is an `Uint8Array` (with [`.iterable()`](#iterablereadableoptions)) or a [`Buffer`](https://nodejs.org/api/buffer.html#class-buffer) (otherwise).521522With [`.readable()`](#readablereadableoptions)/[`.duplex()`](#duplexduplexoptions), the default value is `true`. With [`.iterable()`](#iterablereadableoptions), the default value is `true` if the [`encoding` option](#encoding) is `buffer`, otherwise it is `false`.523524##### readableOptions.preserveNewlines525526Type: `boolean`\499Default: `true`527Default: `false` with [`.iterable()`](#iterablereadableoptions), `true` with [`.readable()`](#readablereadableoptions)/[`.duplex()`](#duplexduplexoptions)528529If both this option and the [`binary` option](#readableoptionsbinary) is `false`, newlines are stripped from each line.530531##### writableOptions
679 unmodified lines