Skip to content
Myr

Allow `stdin`/`stdout`/`stderr` to be an array (#643)

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

authored by ehmicky · committed by GitHub · parent d6b4553 · Browse files · 17 files+620 added−43 removed
This commit

State

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

Diff stats

17 files+620 added−43 removed

  • tests:+336 added−1 removed
  • other:+284 added−42 removed

17 files+620 added−43 removed

modified:lib/stdio/async.js+5 added-5 removed
modified:lib/stdio/direction.js+30 added-1 removed
modified:lib/stdio/handle.js+57 added-8 removed
added:lib/stdio/native.js+48 added
1import process from 'node:process';2import {isStream as isNodeStream} from 'is-stream';34// When we use multiple `stdio` values for the same streams, we pass 'pipe' to `child_process.spawn()`.5// We then emulate the piping done by core Node.js.6// To do so, we transform the following values:7// - Node.js streams are marked as `type: nodeStream`8// - 'inherit' becomes `process.stdin|stdout|stderr`9// - any file descriptor integer becomes `process.stdio[index]`10// All of the above transformations tell Execa to perform manual piping.11export const handleNativeStream = (stdioStream, isStdioArray) => {12 const {type, value, index, optionName} = stdioStream;1314 if (!isStdioArray || type !== 'native') {15 return stdioStream;16 }1718 if (value === 'inherit') {19 return {...stdioStream, type: 'nodeStream', value: getStandardStream(index, value, optionName)};20 }2122 if (typeof value === 'number') {23 return {...stdioStream, type: 'nodeStream', value: getStandardStream(value, value, optionName)};24 }2526 if (isNodeStream(value)) {27 return {...stdioStream, type: 'nodeStream'};28 }2930 return stdioStream;31};3233// Node.js does not allow to easily retrieve file descriptors beyond stdin/stdout/stderr as streams.34// - `fs.createReadStream()`/`fs.createWriteStream()` with the `fd` option do not work with character devices that use blocking reads/writes (such as interactive TTYs).35// - Using a TCP `Socket` would work but be rather complex to implement.36// Since this is an edge case, we simply throw an error message.37// See https://github.com/sindresorhus/execa/pull/643#discussion_r143590570738const getStandardStream = (index, value, optionName) => {39 const standardStream = STANDARD_STREAMS[index];4041 if (standardStream === undefined) {42 throw new TypeError(`The \`${optionName}: ${value}\` option is invalid: no such standard stream.`);43 }4445 return standardStream;46};4748const STANDARD_STREAMS = [process.stdin, process.stdout, process.stderr];
modified:lib/stdio/type.js+4 added-3 removed
35 unmodified lines
36const isReadableStream = stdioOption => Object.prototype.toString.call(stdioOption) === '[object ReadableStream]';37export const isWritableStream = stdioOption => Object.prototype.toString.call(stdioOption) === '[object WritableStream]';38const isWebStream = stdioOption => isReadableStream(stdioOption) || isWritableStream(stdioOption);3940const isIterableObject = stdinOption => typeof stdinOption === 'object'41 && stdinOption !== null42 && (typeof stdinOption[Symbol.asyncIterator] === 'function' || typeof stdinOption[Symbol.iterator] === 'function');40const isIterableObject = stdioOption => typeof stdioOption === 'object'41 && stdioOption !== null42 && !Array.isArray(stdioOption)43 && (typeof stdioOption[Symbol.asyncIterator] === 'function' || typeof stdioOption[Symbol.iterator] === 'function');4445// Convert types to human-friendly strings for error messages46export const TYPE_TO_MESSAGE = {47 filePath: 'a file path',
6 unmodified lines
modified:lib/stream.js+11 added-1 removed
71 unmodified lines
72 const [error] = await once(stream, 'error');73 throw error;74};7576const cleanupStdioStreams = stdioStreams => {77 for (const stdioStream of stdioStreams) {78 if (stdioStream.autoDestroy) {79 stdioStream.value.destroy();80 }81 }82};8384// Retrieve result of child process: exit code, signal, error, streams (stdout/stderr/all)85export const getSpawnedResult = async (86 spawned,87 {encoding, buffer, maxBuffer},
12 unmodified lines
100 allPromise,101 ...stdioStreams.map(stdioStream => waitForStreamEnd(stdioStream, processDone)),102 ]);103 } catch (error) {96 spawned.kill();104 return Promise.all([105 {error, signal: error.signal, timedOut: error.timedOut},106 getBufferedData(spawned.stdout, stdoutPromise),107 getBufferedData(spawned.stderr, stderrPromise),108 getBufferedData(spawned.all, allPromise),109 ]);110 } finally {111 cleanupStdioStreams(stdioStreams);112 spawned.kill();113 }114};
added:test/fixtures/empty.js+1 added
added:test/fixtures/nested-multiple-stderr.js+7 added
added:test/fixtures/nested-multiple-stdin.js+9 added
1#!/usr/bin/env node2import process from 'node:process';3import {execa} from '../../index.js';45const [options] = process.argv.slice(2);6const childProcess = execa('stdin.js', {stdin: JSON.parse(options)});7childProcess.stdin.write('foobar');8const {stdout} = await childProcess;9console.log(stdout);
added:test/fixtures/nested-multiple-stdout.js+7 added
1#!/usr/bin/env node2import process from 'node:process';3import {execa} from '../../index.js';45const [options] = process.argv.slice(2);6const result = await execa('noop.js', ['foobar'], {stdout: JSON.parse(options)});7process.stderr.write(`nested ${result.stdout}`);
added:test/fixtures/nested-stdio.js+26 added
1#!/usr/bin/env node2import process from 'node:process';3import {execa} from '../../index.js';45const [stdioOption, index, file, ...args] = process.argv.slice(2);6let optionValue = JSON.parse(stdioOption);7optionValue = typeof optionValue === 'string' ? process[optionValue] : optionValue;8optionValue = Array.isArray(optionValue) && typeof optionValue[0] === 'string'9 ? [process[optionValue[0]], ...optionValue.slice(1)]10 : optionValue;11const stdio = ['ignore', 'inherit', 'inherit'];12stdio[index] = optionValue;13const childProcess = execa(file, args, {stdio});1415const shouldPipe = Array.isArray(optionValue) && optionValue.includes('pipe');16const hasPipe = childProcess.stdio[index] !== null;1718if (shouldPipe && !hasPipe) {19 throw new Error(`childProcess.stdio[${index}] is null.`);20}2122if (!shouldPipe && hasPipe) {23 throw new Error(`childProcess.stdio[${index}] should be null.`);24}2526await childProcess;
modified:test/fixtures/stdin-fd3.js+1 added-1 removed
1#!/usr/bin/env node2import process from 'node:process';3import {readFileSync} from 'node:fs';45const fileDescriptorIndex = Number(process.argv[3] || 3);5const fileDescriptorIndex = Number(process.argv[2] || 3);6console.log(readFileSync(fileDescriptorIndex, {encoding: 'utf8'}));
added:test/stdio/array.js+257 added
1import {readFile, writeFile, rm} from 'node:fs/promises';2import process from 'node:process';3import {PassThrough} from 'node:stream';4import test from 'ava';5import tempfile from 'tempfile';6import {execa, execaSync} from '../../index.js';7import {getStdinOption, getStdoutOption, getStderrOption, getStdioOption} from '../helpers/stdio.js';8import {setFixtureDir} from '../helpers/fixtures-dir.js';910setFixtureDir();1112const testEmptyArray = (t, getOptions, optionName, execaMethod) => {13 t.throws(() => {14 execaMethod('noop.js', getOptions([]));15 }, {message: `The \`${optionName}\` option must not be an empty array.`});16};1718test('Cannot pass an empty array to stdin', testEmptyArray, getStdinOption, 'stdin', execa);19test('Cannot pass an empty array to stdout', testEmptyArray, getStdoutOption, 'stdout', execa);20test('Cannot pass an empty array to stderr', testEmptyArray, getStderrOption, 'stderr', execa);21test('Cannot pass an empty array to stdio[*]', testEmptyArray, getStdioOption, 'stdio[3]', execa);22test('Cannot pass an empty array to stdin - sync', testEmptyArray, getStdinOption, 'stdin', execaSync);23test('Cannot pass an empty array to stdout - sync', testEmptyArray, getStdoutOption, 'stdout', execaSync);24test('Cannot pass an empty array to stderr - sync', testEmptyArray, getStderrOption, 'stderr', execaSync);25test('Cannot pass an empty array to stdio[*] - sync', testEmptyArray, getStdioOption, 'stdio[3]', execaSync);2627const testNoPipeOption = async (t, stdioOption, streamName) => {28 const childProcess = execa('empty.js', {[streamName]: stdioOption});29 t.is(childProcess[streamName], null);30 await execa;31};3233test('stdin can be "ignore"', testNoPipeOption, 'ignore', 'stdin');34test('stdin can be ["ignore"]', testNoPipeOption, ['ignore'], 'stdin');35test('stdin can be ["ignore", "ignore"]', testNoPipeOption, ['ignore', 'ignore'], 'stdin');36test('stdin can be "ipc"', testNoPipeOption, 'ipc', 'stdin');37test('stdin can be ["ipc"]', testNoPipeOption, ['ipc'], 'stdin');38test('stdin can be "inherit"', testNoPipeOption, 'inherit', 'stdin');39test('stdin can be ["inherit"]', testNoPipeOption, ['inherit'], 'stdin');40test('stdin can be 0', testNoPipeOption, 0, 'stdin');41test('stdin can be [0]', testNoPipeOption, [0], 'stdin');42test('stdout can be "ignore"', testNoPipeOption, 'ignore', 'stdout');43test('stdout can be ["ignore"]', testNoPipeOption, ['ignore'], 'stdout');44test('stdout can be ["ignore", "ignore"]', testNoPipeOption, ['ignore', 'ignore'], 'stdout');45test('stdout can be "ipc"', testNoPipeOption, 'ipc', 'stdout');46test('stdout can be ["ipc"]', testNoPipeOption, ['ipc'], 'stdout');47test('stdout can be "inherit"', testNoPipeOption, 'inherit', 'stdout');48test('stdout can be ["inherit"]', testNoPipeOption, ['inherit'], 'stdout');49test('stdout can be 1', testNoPipeOption, 1, 'stdout');50test('stdout can be [1]', testNoPipeOption, [1], 'stdout');51test('stderr can be "ignore"', testNoPipeOption, 'ignore', 'stderr');52test('stderr can be ["ignore"]', testNoPipeOption, ['ignore'], 'stderr');53test('stderr can be ["ignore", "ignore"]', testNoPipeOption, ['ignore', 'ignore'], 'stderr');54test('stderr can be "ipc"', testNoPipeOption, 'ipc', 'stderr');55test('stderr can be ["ipc"]', testNoPipeOption, ['ipc'], 'stderr');56test('stderr can be "inherit"', testNoPipeOption, 'inherit', 'stderr');57test('stderr can be ["inherit"]', testNoPipeOption, ['inherit'], 'stderr');58test('stderr can be 2', testNoPipeOption, 2, 'stderr');59test('stderr can be [2]', testNoPipeOption, [2], 'stderr');6061const testNoPipeStdioOption = async (t, stdioOption) => {62 const childProcess = execa('empty.js', {stdio: ['pipe', 'pipe', 'pipe', stdioOption]});63 t.is(childProcess.stdio[3], null);64 await execa;65};6667test('stdio[*] can be "ignore"', testNoPipeStdioOption, 'ignore');68test('stdio[*] can be ["ignore"]', testNoPipeStdioOption, ['ignore']);69test('stdio[*] can be ["ignore", "ignore"]', testNoPipeStdioOption, ['ignore', 'ignore']);70test('stdio[*] can be "ipc"', testNoPipeStdioOption, 'ipc');71test('stdio[*] can be ["ipc"]', testNoPipeStdioOption, ['ipc']);72test('stdio[*] can be "inherit"', testNoPipeStdioOption, 'inherit');73test('stdio[*] can be ["inherit"]', testNoPipeStdioOption, ['inherit']);74test('stdio[*] can be 3', testNoPipeStdioOption, 3);75test('stdio[*] can be [3]', testNoPipeStdioOption, [3]);7677const testInvalidArrayValue = (t, invalidStdio, getOptions, execaMethod) => {78 t.throws(() => {79 execaMethod('noop.js', getOptions(['pipe', invalidStdio]));80 }, {message: /must not include/});81};8283test('Cannot pass "ignore" and another value to stdin', testInvalidArrayValue, 'ignore', getStdinOption, execa);84test('Cannot pass "ignore" and another value to stdout', testInvalidArrayValue, 'ignore', getStdoutOption, execa);85test('Cannot pass "ignore" and another value to stderr', testInvalidArrayValue, 'ignore', getStderrOption, execa);86test('Cannot pass "ignore" and another value to stdio[*]', testInvalidArrayValue, 'ignore', getStdioOption, execa);87test('Cannot pass "ignore" and another value to stdin - sync', testInvalidArrayValue, 'ignore', getStdinOption, execaSync);88test('Cannot pass "ignore" and another value to stdout - sync', testInvalidArrayValue, 'ignore', getStdoutOption, execaSync);89test('Cannot pass "ignore" and another value to stderr - sync', testInvalidArrayValue, 'ignore', getStderrOption, execaSync);90test('Cannot pass "ignore" and another value to stdio[*] - sync', testInvalidArrayValue, 'ignore', getStdioOption, execaSync);91test('Cannot pass "ipc" and another value to stdin', testInvalidArrayValue, 'ipc', getStdinOption, execa);92test('Cannot pass "ipc" and another value to stdout', testInvalidArrayValue, 'ipc', getStdoutOption, execa);93test('Cannot pass "ipc" and another value to stderr', testInvalidArrayValue, 'ipc', getStderrOption, execa);94test('Cannot pass "ipc" and another value to stdio[*]', testInvalidArrayValue, 'ipc', getStdioOption, execa);95test('Cannot pass "ipc" and another value to stdin - sync', testInvalidArrayValue, 'ipc', getStdinOption, execaSync);96test('Cannot pass "ipc" and another value to stdout - sync', testInvalidArrayValue, 'ipc', getStdoutOption, execaSync);97test('Cannot pass "ipc" and another value to stderr - sync', testInvalidArrayValue, 'ipc', getStderrOption, execaSync);98test('Cannot pass "ipc" and another value to stdio[*] - sync', testInvalidArrayValue, 'ipc', getStdioOption, execaSync);99100const testInputOutput = (t, stdioOption, execaMethod) => {101 t.throws(() => {102 execaMethod('noop.js', getStdioOption([new ReadableStream(), stdioOption]));103 }, {message: /readable and writable/});104};105106test('Cannot pass both readable and writable values to stdio[*] - WritableStream', testInputOutput, new WritableStream(), execa);107test('Cannot pass both readable and writable values to stdio[*] - 1', testInputOutput, 1, execa);108test('Cannot pass both readable and writable values to stdio[*] - 2', testInputOutput, 2, execa);109test('Cannot pass both readable and writable values to stdio[*] - process.stdout', testInputOutput, process.stdout, execa);110test('Cannot pass both readable and writable values to stdio[*] - process.stderr', testInputOutput, process.stderr, execa);111test('Cannot pass both readable and writable values to stdio[*] - WritableStream - sync', testInputOutput, new WritableStream(), execaSync);112test('Cannot pass both readable and writable values to stdio[*] - 1 - sync', testInputOutput, 1, execaSync);113test('Cannot pass both readable and writable values to stdio[*] - 2 - sync', testInputOutput, 2, execaSync);114test('Cannot pass both readable and writable values to stdio[*] - process.stdout - sync', testInputOutput, process.stdout, execaSync);115test('Cannot pass both readable and writable values to stdio[*] - process.stderr - sync', testInputOutput, process.stderr, execaSync);116117const testAmbiguousDirection = async (t, execaMethod) => {118 const [filePathOne, filePathTwo] = [tempfile(), tempfile()];119 await execaMethod('noop-fd3.js', ['foobar'], getStdioOption([filePathOne, filePathTwo]));120 t.deepEqual(await Promise.all([readFile(filePathOne, 'utf8'), readFile(filePathTwo, 'utf8')]), ['foobar\n', 'foobar\n']);121 await Promise.all([rm(filePathOne), rm(filePathTwo)]);122};123124test('stdio[*] default direction is output', testAmbiguousDirection, execa);125test('stdio[*] default direction is output - sync', testAmbiguousDirection, execaSync);126127const testAmbiguousMultiple = async (t, stdioOptions) => {128 const filePath = tempfile();129 await writeFile(filePath, 'foobar');130 const {stdout} = await execa('stdin-fd3.js', getStdioOption([filePath, ...stdioOptions]));131 t.is(stdout, 'foobar');132 await rm(filePath);133};134135test('stdio[*] ambiguous direction is influenced by other values like ReadableStream', testAmbiguousMultiple, [new ReadableStream()]);136test('stdio[*] ambiguous direction is influenced by other values like 0', testAmbiguousMultiple, [0]);137test('stdio[*] ambiguous direction is influenced by other values like process.stdin', testAmbiguousMultiple, [process.stdin]);138test('stdio[*] Duplex has an ambiguous direction like ReadableStream', testAmbiguousMultiple, [new PassThrough(), new ReadableStream()]);139test('stdio[*] Duplex has an ambiguous direction like 0', testAmbiguousMultiple, [new PassThrough(), 0]);140test('stdio[*] Duplex has an ambiguous direction like process.stdin', testAmbiguousMultiple, [new PassThrough(), process.stdin]);141142const testRedirectInput = async (t, stdioOption, index, fixtureName) => {143 const {stdout} = await execa('nested-stdio.js', [JSON.stringify(stdioOption), String(index), fixtureName], {input: 'foobar'});144 t.is(stdout, 'foobar');145};146147test.serial('stdio[*] can be 0', testRedirectInput, 0, 3, 'stdin-fd3.js');148test.serial('stdio[*] can be [0]', testRedirectInput, [0], 3, 'stdin-fd3.js');149test.serial('stdio[*] can be [0, "pipe"]', testRedirectInput, [0, 'pipe'], 3, 'stdin-fd3.js');150test.serial('stdio[*] can be process.stdin', testRedirectInput, 'stdin', 3, 'stdin-fd3.js');151test.serial('stdio[*] can be [process.stdin]', testRedirectInput, ['stdin'], 3, 'stdin-fd3.js');152test.serial('stdio[*] can be [process.stdin, "pipe"]', testRedirectInput, ['stdin', 'pipe'], 3, 'stdin-fd3.js');153154const OUTPUT_DESCRIPTOR_FIXTURES = ['noop.js', 'noop-err.js', 'noop-fd3.js'];155156const isStdoutDescriptor = stdioOption => stdioOption === 1157 || stdioOption === 'stdout'158 || (Array.isArray(stdioOption) && isStdoutDescriptor(stdioOption[0]));159160const testRedirectOutput = async (t, stdioOption, index) => {161 const fixtureName = OUTPUT_DESCRIPTOR_FIXTURES[index - 1];162 const result = await execa('nested-stdio.js', [JSON.stringify(stdioOption), String(index), fixtureName, 'foobar']);163 const streamName = isStdoutDescriptor(stdioOption) ? 'stdout' : 'stderr';164 t.is(result[streamName], 'foobar');165};166167test('stdout can be 2', testRedirectOutput, 2, 1);168test('stdout can be [2]', testRedirectOutput, [2], 1);169test('stdout can be [2, "pipe"]', testRedirectOutput, [2, 'pipe'], 1);170test('stdout can be process.stderr', testRedirectOutput, 'stderr', 1);171test('stdout can be [process.stderr]', testRedirectOutput, ['stderr'], 1);172test('stdout can be [process.stderr, "pipe"]', testRedirectOutput, ['stderr', 'pipe'], 1);173test('stderr can be 1', testRedirectOutput, 1, 2);174test('stderr can be [1]', testRedirectOutput, [1], 2);175test('stderr can be [1, "pipe"]', testRedirectOutput, [1, 'pipe'], 2);176test('stderr can be process.stdout', testRedirectOutput, 'stdout', 2);177test('stderr can be [process.stdout]', testRedirectOutput, ['stdout'], 2);178test('stderr can be [process.stdout, "pipe"]', testRedirectOutput, ['stdout', 'pipe'], 2);179test('stdio[*] can be 1', testRedirectOutput, 1, 3);180test('stdio[*] can be [1]', testRedirectOutput, [1], 3);181test('stdio[*] can be [1, "pipe"]', testRedirectOutput, [1, 'pipe'], 3);182test('stdio[*] can be 2', testRedirectOutput, 2, 3);183test('stdio[*] can be [2]', testRedirectOutput, [2], 3);184test('stdio[*] can be [2, "pipe"]', testRedirectOutput, [2, 'pipe'], 3);185test('stdio[*] can be process.stdout', testRedirectOutput, 'stdout', 3);186test('stdio[*] can be [process.stdout]', testRedirectOutput, ['stdout'], 3);187test('stdio[*] can be [process.stdout, "pipe"]', testRedirectOutput, ['stdout', 'pipe'], 3);188test('stdio[*] can be process.stderr', testRedirectOutput, 'stderr', 3);189test('stdio[*] can be [process.stderr]', testRedirectOutput, ['stderr'], 3);190test('stdio[*] can be [process.stderr, "pipe"]', testRedirectOutput, ['stderr', 'pipe'], 3);191192const testInheritStdin = async (t, stdin) => {193 const {stdout} = await execa('nested-multiple-stdin.js', [JSON.stringify(stdin)], {input: 'foobar'});194 t.is(stdout, 'foobarfoobar');195};196197test('stdin can be ["inherit", "pipe"]', testInheritStdin, ['inherit', 'pipe']);198test('stdin can be [0, "pipe"]', testInheritStdin, [0, 'pipe']);199200const testInheritStdout = async (t, stdout) => {201 const result = await execa('nested-multiple-stdout.js', [JSON.stringify(stdout)]);202 t.is(result.stdout, 'foobar');203 t.is(result.stderr, 'nested foobar');204};205206test('stdout can be ["inherit", "pipe"]', testInheritStdout, ['inherit', 'pipe']);207test('stdout can be [1, "pipe"]', testInheritStdout, [1, 'pipe']);208209const testInheritStderr = async (t, stderr) => {210 const result = await execa('nested-multiple-stderr.js', [JSON.stringify(stderr)]);211 t.is(result.stdout, 'nested foobar');212 t.is(result.stderr, 'foobar');213};214215test('stderr can be ["inherit", "pipe"]', testInheritStderr, ['inherit', 'pipe']);216test('stderr can be [2, "pipe"]', testInheritStderr, [2, 'pipe']);217218const testOverflowStream = async (t, stdio) => {219 const {stdout} = await execa('nested.js', [JSON.stringify({stdio}), 'empty.js'], {stdio: ['pipe', 'pipe', 'pipe', 'pipe']});220 t.is(stdout, '');221};222223if (process.platform === 'linux') {224 test('stdin can use 4+', testOverflowStream, [4, 'pipe', 'pipe', 'pipe']);225 test('stdin can use [4+]', testOverflowStream, [[4], 'pipe', 'pipe', 'pipe']);226 test('stdout can use 4+', testOverflowStream, ['pipe', 4, 'pipe', 'pipe']);227 test('stdout can use [4+]', testOverflowStream, ['pipe', [4], 'pipe', 'pipe']);228 test('stderr can use 4+', testOverflowStream, ['pipe', 'pipe', 4, 'pipe']);229 test('stderr can use [4+]', testOverflowStream, ['pipe', 'pipe', [4], 'pipe']);230 test('stdio[*] can use 4+', testOverflowStream, ['pipe', 'pipe', 'pipe', 4]);231 test('stdio[*] can use [4+]', testOverflowStream, ['pipe', 'pipe', 'pipe', [4]]);232}233234test('stdio[*] can use "inherit"', testOverflowStream, ['pipe', 'pipe', 'pipe', 'inherit']);235test('stdio[*] can use ["inherit"]', testOverflowStream, ['pipe', 'pipe', 'pipe', ['inherit']]);236237const testOverflowStreamArray = (t, stdio) => {238 t.throws(() => {239 execa('noop.js', {stdio});240 }, {message: /no such standard stream/});241};242243test('stdin cannot use 4+ and another value', testOverflowStreamArray, [[4, 'pipe'], 'pipe', 'pipe', 'pipe']);244test('stdout cannot use 4+ and another value', testOverflowStreamArray, ['pipe', [4, 'pipe'], 'pipe', 'pipe']);245test('stderr cannot use 4+ and another value', testOverflowStreamArray, ['pipe', 'pipe', [4, 'pipe'], 'pipe']);246test('stdio[*] cannot use 4+ and another value', testOverflowStreamArray, ['pipe', 'pipe', 'pipe', [4, 'pipe']]);247test('stdio[*] cannot use "inherit" and another value', testOverflowStreamArray, ['pipe', 'pipe', 'pipe', ['inherit', 'pipe']]);248249const testOverlapped = async (t, getOptions) => {250 const {stdout} = await execa('noop.js', ['foobar'], getOptions(['overlapped', 'pipe']));251 t.is(stdout, 'foobar');252};253254test('stdin can be ["overlapped", "pipe"]', testOverlapped, getStdinOption);255test('stdout can be ["overlapped", "pipe"]', testOverlapped, getStdoutOption);256test('stderr can be ["overlapped", "pipe"]', testOverlapped, getStderrOption);257test('stdio[*] can be ["overlapped", "pipe"]', testOverlapped, getStdioOption);
modified:test/stdio/node-stream.js+28 added
73 unmodified lines
7475test('stdout can be a Node.js Writable with a file descriptor', testFileWritable, getStdoutOption, 'noop.js');76test('stderr can be a Node.js Writable with a file descriptor', testFileWritable, getStderrOption, 'noop-err.js');77test('stdio[*] can be a Node.js Writable with a file descriptor', testFileWritable, getStdioOption, 'noop-fd3.js');7879const testLazyFileReadable = async (t, fixtureName, getOptions) => {80 const filePath = tempfile();81 await writeFile(filePath, 'foobar');82 const stream = createReadStream(filePath);8384 const {stdout} = await execa(fixtureName, getOptions([stream, 'pipe']));85 t.is(stdout, 'foobar');8687 await rm(filePath);88};8990test('stdin can be [Readable, "pipe"] without a file descriptor', testLazyFileReadable, 'stdin.js', getStdinOption);91test('stdio[*] can be [Readable, "pipe"] without a file descriptor', testLazyFileReadable, 'stdin-fd3.js', getStdioOption);9293const testLazyFileWritable = async (t, getOptions, fixtureName) => {94 const filePath = tempfile();95 const stream = createWriteStream(filePath);9697 await execa(fixtureName, ['foobar'], getOptions([stream, 'pipe']));98 t.is(await readFile(filePath, 'utf8'), 'foobar\n');99100 await rm(filePath);101};102103test('stdout can be [Writable, "pipe"] without a file descriptor', testLazyFileWritable, getStdoutOption, 'noop.js');104test('stderr can be [Writable, "pipe"] without a file descriptor', testLazyFileWritable, getStderrOption, 'noop-err.js');105test('stdio[*] can be [Writable, "pipe"] without a file descriptor', testLazyFileWritable, getStdioOption, 'noop-fd3.js');
modified:index.d.ts+26 added-13 removed
23 unmodified lines
24type OutputStdioOption =25 | Writable26 | WritableStream;2728export type StdinOption = CommonStdioOption | InputStdioOption;29export type StdoutStderrOption = CommonStdioOption | OutputStdioOption;30export type StdioOption = CommonStdioOption | InputStdioOption | OutputStdioOption;28export type StdinOption =29 CommonStdioOption | InputStdioOption30 | Array<CommonStdioOption | InputStdioOption>;31export type StdoutStderrOption =32 CommonStdioOption | OutputStdioOption33 | Array<CommonStdioOption | OutputStdioOption>;34export type StdioOption =35 CommonStdioOption | InputStdioOption | OutputStdioOption36 | Array<CommonStdioOption | InputStdioOption | OutputStdioOption>;3738type StdioOptions =39 | BaseStdioOption40 | readonly [StdinOption, StdoutStderrOption, StdoutStderrOption, ...StdioOption[]];
83 unmodified lines
124 - file URL.125 - web [`ReadableStream`](https://developer.mozilla.org/en-US/docs/Web/API/ReadableStream).126 - [`Iterable`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#the_iterable_protocol) or [`AsyncIterable`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#the_async_iterator_and_async_iterable_protocols)127128 This can be an [array of values](https://github.com/sindresorhus/execa#redirect-stdinstdoutstderr-to-multiple-destinations) such as `['inherit', 'pipe']` or `[filePath, 'pipe']`.129130 @default `inherit` with `$`, `pipe` otherwise131 */132 readonly stdin?: StdinOption;133
11 unmodified lines
145 - file path. If relative, it must start with `.`.146 - file URL.147 - web [`WritableStream`](https://developer.mozilla.org/en-US/docs/Web/API/WritableStream).148149 This can be an [array of values](https://github.com/sindresorhus/execa#redirect-stdinstdoutstderr-to-multiple-destinations) such as `['inherit', 'pipe']` or `[filePath, 'pipe']`.150151 @default 'pipe'152 */153 readonly stdout?: StdoutStderrOption;154
11 unmodified lines
166 - file path. If relative, it must start with `.`.167 - file URL.168 - web [`WritableStream`](https://developer.mozilla.org/en-US/docs/Web/API/WritableStream).169170 This can be an [array of values](https://github.com/sindresorhus/execa#redirect-stdinstdoutstderr-to-multiple-destinations) such as `['inherit', 'pipe']` or `[filePath, 'pipe']`.171172 @default 'pipe'173 */174 readonly stderr?: StdoutStderrOption;175176 /**177 Like the `stdin`, `stdout` and `stderr` options but for all file descriptors at once. For example, `{stdio: ['ignore', 'pipe', 'pipe']}` is the same as `{stdin: 'ignore', stdout: 'pipe', stderr: 'pipe'}`.178179 A single string can be used as a shortcut. For example, `{stdio: 'pipe'}` is the same as `{stdin: 'pipe', stdout: 'pipe', stderr: 'pipe'}`.180181 The array can have more than 3 items, to create additional file descriptors beyond `stdin`/`stdout`/`stderr`. For example, `{stdio: ['pipe', 'pipe', 'pipe', 'ipc']}` sets a fourth file descriptor `'ipc'`.182183 @default 'pipe'184 */185 readonly stdio?: StdioOptions;186187 /**188 Setting this to `false` resolves the promise with the error instead of rejecting it.189190 @default true191 */
39 unmodified lines
231 */232 readonly argv0?: string;233234 /**212 Like the `stdin`, `stdout` and `stderr` options but for all file descriptors at once.213 The possible values are the same except it can also be:214 - a single string, to set the same value to each standard stream.215 - an array with more than 3 values, to create more than 3 file descriptors.216217 @default 'pipe'218 */219 readonly stdio?: StdioOptions;220221 /**235 Specify the kind of serialization used for sending messages between processes when using the `stdio: 'ipc'` option or `execaNode()`:236 - `json`: Uses `JSON.stringify()` and `JSON.parse()`.237 - `advanced`: Uses [`v8.serialize()`](https://nodejs.org/api/v8.html#v8_v8_serialize_value)238
844 unmodified lines
modified:index.test-d.ts+76 added-3 removed
158 unmodified lines
159execa('unicorns', {input: process.stdin});160execa('unicorns', {inputFile: ''});161execa('unicorns', {inputFile: fileUrl});162execa('unicorns', {stdin: 'pipe'});163execa('unicorns', {stdin: ['pipe']});164execa('unicorns', {stdin: 'overlapped'});165execa('unicorns', {stdin: ['overlapped']});166execa('unicorns', {stdin: 'ipc'});167execa('unicorns', {stdin: ['ipc']});168execa('unicorns', {stdin: 'ignore'});169execa('unicorns', {stdin: ['ignore']});170execa('unicorns', {stdin: 'inherit'});171execa('unicorns', {stdin: ['inherit']});172execa('unicorns', {stdin: process.stdin});173execa('unicorns', {stdin: [process.stdin]});174execa('unicorns', {stdin: new Readable()});175execa('unicorns', {stdin: [new Readable()]});176expectError(execa('unicorns', {stdin: new Writable()}));177expectError(execa('unicorns', {stdin: [new Writable()]}));178execa('unicorns', {stdin: new ReadableStream()});179execa('unicorns', {stdin: [new ReadableStream()]});180expectError(execa('unicorns', {stdin: new WritableStream()}));172execa('unicorns', {stdin: ['']});173execa('unicorns', {stdin: [new Uint8Array(0)]});181expectError(execa('unicorns', {stdin: [new WritableStream()]}));182execa('unicorns', {stdin: stringGenerator()});183execa('unicorns', {stdin: [stringGenerator()]});184execa('unicorns', {stdin: binaryGenerator()});185execa('unicorns', {stdin: [binaryGenerator()]});186execa('unicorns', {stdin: asyncStringGenerator()});177expectError(execa('unicorns', {stdin: [0]}));187execa('unicorns', {stdin: [asyncStringGenerator()]});188expectError(execa('unicorns', {stdin: numberGenerator()}));189expectError(execa('unicorns', {stdin: [numberGenerator()]}));190execa('unicorns', {stdin: fileUrl});191execa('unicorns', {stdin: [fileUrl]});192execa('unicorns', {stdin: './test'});193execa('unicorns', {stdin: ['./test']});194execa('unicorns', {stdin: 1});195execa('unicorns', {stdin: [1]});196execa('unicorns', {stdin: undefined});197execa('unicorns', {stdin: [undefined]});198execa('unicorns', {stdin: ['pipe', 'inherit']});199execa('unicorns', {stdout: 'pipe'});200execa('unicorns', {stdout: ['pipe']});201execa('unicorns', {stdout: 'overlapped'});202execa('unicorns', {stdout: ['overlapped']});203execa('unicorns', {stdout: 'ipc'});204execa('unicorns', {stdout: ['ipc']});205execa('unicorns', {stdout: 'ignore'});206execa('unicorns', {stdout: ['ignore']});207execa('unicorns', {stdout: 'inherit'});208execa('unicorns', {stdout: ['inherit']});209execa('unicorns', {stdout: process.stdout});210execa('unicorns', {stdout: [process.stdout]});211execa('unicorns', {stdout: new Writable()});212execa('unicorns', {stdout: [new Writable()]});213expectError(execa('unicorns', {stdout: new Readable()}));214expectError(execa('unicorn', {stdout: [new Readable()]}));215execa('unicorns', {stdout: new WritableStream()});216execa('unicorns', {stdout: [new WritableStream()]});217expectError(execa('unicorns', {stdout: new ReadableStream()}));218expectError(execa('unicorn', {stdout: [new ReadableStream()]}));219execa('unicorns', {stdout: fileUrl});220execa('unicorns', {stdout: [fileUrl]});221execa('unicorns', {stdout: './test'});222execa('unicorns', {stdout: ['./test']});223execa('unicorns', {stdout: 1});224execa('unicorns', {stdout: [1]});225execa('unicorns', {stdout: undefined});226execa('unicorns', {stdout: [undefined]});227execa('unicorns', {stdout: ['pipe', 'inherit']});228execa('unicorns', {stderr: 'pipe'});229execa('unicorns', {stderr: ['pipe']});230execa('unicorns', {stderr: 'overlapped'});231execa('unicorns', {stderr: ['overlapped']});232execa('unicorns', {stderr: 'ipc'});233execa('unicorns', {stderr: ['ipc']});234execa('unicorns', {stderr: 'ignore'});235execa('unicorns', {stderr: ['ignore']});236execa('unicorns', {stderr: 'inherit'});237execa('unicorns', {stderr: ['inherit']});238execa('unicorns', {stderr: process.stderr});239execa('unicorns', {stderr: [process.stderr]});240execa('unicorns', {stderr: new Writable()});241execa('unicorns', {stderr: [new Writable()]});242expectError(execa('unicorns', {stderr: new Readable()}));243expectError(execa('unicorns', {stderr: [new Readable()]}));244execa('unicorns', {stderr: new WritableStream()});245execa('unicorns', {stderr: [new WritableStream()]});246expectError(execa('unicorns', {stderr: new ReadableStream()}));247expectError(execa('unicorns', {stderr: [new ReadableStream()]}));248execa('unicorns', {stderr: fileUrl});249execa('unicorns', {stderr: [fileUrl]});250execa('unicorns', {stderr: './test'});251execa('unicorns', {stderr: ['./test']});252execa('unicorns', {stderr: 1});253execa('unicorns', {stderr: [1]});254execa('unicorns', {stderr: undefined});255execa('unicorns', {stderr: [undefined]});256execa('unicorns', {stderr: ['pipe', 'inherit']});257execa('unicorns', {all: true});258execa('unicorns', {reject: false});259execa('unicorns', {stripFinalNewline: false});260execa('unicorns', {extendEnv: false});
17 unmodified lines
278expectError(execa('unicorns', {stdio: stringGenerator()}));279expectError(execa('unicorns', {stdio: asyncStringGenerator()}));280expectError(execa('unicorns', {stdio: ['pipe', 'pipe']}));281execa('unicorns', {stdio: [new Readable(), 'pipe', 'pipe']});282execa('unicorns', {stdio: [[new Readable()], ['pipe'], ['pipe']]});283execa('unicorns', {stdio: ['pipe', new Writable(), 'pipe']});284execa('unicorns', {stdio: [['pipe'], [new Writable()], ['pipe']]});285execa('unicorns', {stdio: ['pipe', 'pipe', new Writable()]});286execa('unicorns', {stdio: [['pipe'], ['pipe'], [new Writable()]]});287expectError(execa('unicorns', {stdio: [new Writable(), 'pipe', 'pipe']}));288expectError(execa('unicorns', {stdio: [[new Writable()], ['pipe'], ['pipe']]}));289expectError(execa('unicorns', {stdio: ['pipe', new Readable(), 'pipe']}));290expectError(execa('unicorns', {stdio: [['pipe'], [new Readable()], ['pipe']]}));291expectError(execa('unicorns', {stdio: ['pipe', 'pipe', new Readable()]}));292expectError(execa('unicorns', {stdio: [['pipe'], ['pipe'], [new Readable()]]}));293execa('unicorns', {294 stdio: [295 'pipe',296 'overlapped',
12 unmodified lines
309 stringGenerator(),310 asyncStringGenerator(),311 ],312});313execa('unicorns', {314 stdio: [315 ['pipe'],316 ['pipe', 'inherit'],317 ['overlapped'],318 ['ipc'],319 ['ignore'],320 ['inherit'],321 [process.stdin],322 [1],323 [undefined],324 [fileUrl],325 ['./test'],326 [new Writable()],327 [new Readable()],328 [new WritableStream()],329 [new ReadableStream()],330 [stringGenerator()],331 [asyncStringGenerator()],332 ],333});334execa('unicorns', {serialization: 'advanced'});335execa('unicorns', {detached: true});336execa('unicorns', {uid: 0});337execa('unicorns', {gid: 0});
146 unmodified lines
modified:readme.md+27 added-8 removed
567 unmodified lines
568See also the [`input`](#input) and [`stdin`](#stdin) options.569570#### stdin571572Type: `string | number | stream.Readable | ReadableStream | URL | Iterable<string | Uint8Array> | AsyncIterable<string | Uint8Array>`\572Type: `string | number | stream.Readable | ReadableStream | URL | Iterable<string | Uint8Array> | AsyncIterable<string | Uint8Array>` (or a tuple of those types)\573Default: `inherit` with [`$`](#command), `pipe` otherwise574575[How to setup](https://nodejs.org/api/child_process.html#child_process_options_stdio) the child process' standard input. This can be:576- `'pipe'`: Sets [`childProcess.stdin`](https://nodejs.org/api/child_process.html#subprocessstdin) stream.
9 unmodified lines
586- file URL.587- web [`ReadableStream`](https://developer.mozilla.org/en-US/docs/Web/API/ReadableStream).588- [`Iterable`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#the_iterable_protocol) or [`AsyncIterable`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#the_async_iterator_and_async_iterable_protocols)589590This can be an [array of values](#redirect-stdinstdoutstderr-to-multiple-destinations) such as `['inherit', 'pipe']` or `[filePath, 'pipe']`.591592#### stdout593592Type: `string | number | stream.Writable | WritableStream | URL`\594Type: `string | number | stream.Writable | WritableStream | URL` (or a tuple of those types)\595Default: `pipe`596597[How to setup](https://nodejs.org/api/child_process.html#child_process_options_stdio) the child process' standard output. This can be:598- `'pipe'`: Sets [`childProcessResult.stdout`](#stdout) (as a string or `Uint8Array`) and [`childProcess.stdout`](https://nodejs.org/api/child_process.html#subprocessstdout) (as a stream).
8 unmodified lines
607- file path. If relative, it must start with `.`.608- file URL.609- web [`WritableStream`](https://developer.mozilla.org/en-US/docs/Web/API/WritableStream).610611This can be an [array of values](#redirect-stdinstdoutstderr-to-multiple-destinations) such as `['inherit', 'pipe']` or `[filePath, 'pipe']`.612613#### stderr614611Type: `string | number | stream.Writable | WritableStream | URL`\615Type: `string | number | stream.Writable | WritableStream | URL` (or a tuple of those types)`\616Default: `pipe`617618[How to setup](https://nodejs.org/api/child_process.html#child_process_options_stdio) the child process' standard error. This can be:619- `'pipe'`: Sets [`childProcessResult.stderr`](#stderr) (as a string or `Uint8Array`) and [`childProcess.stderr`](https://nodejs.org/api/child_process.html#subprocessstderr) (as a stream).
8 unmodified lines
628- file path. If relative, it must start with `.`.629- file URL.630- web [`WritableStream`](https://developer.mozilla.org/en-US/docs/Web/API/WritableStream).631632This can be an [array of values](#redirect-stdinstdoutstderr-to-multiple-destinations) such as `['inherit', 'pipe']` or `[filePath, 'pipe']`.633634#### stdio635630Type: `string | [StdinOption, StdoutOption, StderrOption] | StdioOption[]`\636Type: `string | Array<string | number | stream.Readable | stream.Writable | ReadableStream | WritableStream | URL | Iterable<string | Uint8Array> | AsyncIterable<string | Uint8Array>>` (or a tuple of those types)\637Default: `pipe`638633Like the [`stdin`](#stdin), [`stdout`](#stdout-1) and [`stderr`](#stderr-1) options but for all file descriptors at once.\634The possible values are the same except it can also be:635- a single string, to set the same value to each standard stream.636- an array with more than 3 values, to create more than 3 file descriptors.639Like the [`stdin`](#stdin), [`stdout`](#stdout-1) and [`stderr`](#stderr-1) options but for all file descriptors at once. For example, `{stdio: ['ignore', 'pipe', 'pipe']}` is the same as `{stdin: 'ignore', stdout: 'pipe', stderr: 'pipe'}`.640641A single string can be used as a shortcut. For example, `{stdio: 'pipe'}` is the same as `{stdin: 'pipe', stdout: 'pipe', stderr: 'pipe'}`.642643The array can have more than 3 items, to create additional file descriptors beyond `stdin`/`stdout`/`stderr`. For example, `{stdio: ['pipe', 'pipe', 'pipe', 'ipc']}` sets a fourth file descriptor `'ipc'`.644645#### all646647Type: `boolean`\648Default: `false`
160 unmodified lines
809List of [CLI options](https://nodejs.org/api/cli.html#cli_options) passed to the Node.js executable.810811## Tips812813### Redirect stdin/stdout/stderr to multiple destinations814815The [`stdin`](#stdin), [`stdout`](#stdout-1) and [`stderr`](#stderr-1) options can be an array of values.816The following example redirects `stdout` to both the terminal and an `output.txt` file, while also retrieving its value programmatically.817818```js819const {stdout} = await execa('npm', ['install'], {stdout: ['inherit', './output.txt', 'pipe']})820console.log(stdout);821```822823When combining `inherit` with other values, please note that the child process will not be an interactive TTY, even if the parent process is one.824825### Retry on error826827Gracefully handle failures by using automatic retries and exponential backoff with the [`p-retry`](https://github.com/sindresorhus/p-retry) package:828
84 unmodified lines