Skip to content
Myr

Rename `spawned` and `child process` to `subprocess` (#897)

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

authored by ehmicky · committed by GitHub · parent 1915060 · Browse files · 92 files+1201 added−1200 removed
This commit

State

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

Diff stats

92 files+1201 added−1200 removed

  • tests:+671 added−671 removed
  • other:+530 added−529 removed

92 files+1201 added−1200 removed

modified:docs/scripts.md+11 added-11 removed
3 unmodified lines
4 - [performant](#performance)5 - [cross-platform](#shell): [no shell](../readme.md#shell-syntax) is used, only JavaScript.6 - [secure](#escaping): no shell injection.7 - [simple](#simplicity): minimalistic API, no [globals](#global-variables), no [binary](#main-binary), no [builtin CLI utilities](#builtin-utilities).8 - [featureful](#simplicity): all Execa features are available ([process piping](#piping-stdout-to-another-command), [IPC](#ipc), [transforms](#transforms), [background processes](#background-processes), [cancellation](#cancellation), [local binaries](#local-binaries), [cleanup on exit](../readme.md#cleanup), [interleaved output](#interleaved-output), [forceful termination](../readme.md#forcekillafterdelay), etc.).8 - [featureful](#simplicity): all Execa features are available ([subprocess piping](#piping-stdout-to-another-command), [IPC](#ipc), [transforms](#transforms), [background subprocesses](#background-subprocesses), [cancellation](#cancellation), [local binaries](#local-binaries), [cleanup on exit](../readme.md#cleanup), [interleaved output](#interleaved-output), [forceful termination](../readme.md#forcekillafterdelay), etc.).9 - [easy to debug](#debugging): [verbose mode](#verbose-mode), [detailed errors](#errors), [messages and stack traces](#cancellation), stateless API.1011```js12import {$} from 'execa';
630 unmodified lines
643await $({cwd: 'project'})`pwd`;644await $`pwd`;645```646647### Background processes647### Background subprocesses648649```sh650# Bash651echo one &
19 unmodified lines
671```672673```js674// Execa675const childProcess = $({ipc: true})`node script.js`;675const subprocess = $({ipc: true})`node script.js`;676677childProcess.on('message', message => {677subprocess.on('message', message => {678 if (message === 'ping') {679 childProcess.send('pong');679 subprocess.send('pong');680 }681});682```683
26 unmodified lines
710```711712```js713// zx714childProcess.kill();714subprocess.kill();715```716717```js718// Execa719// Can specify an error message and stack trace720childProcess.kill(error);720subprocess.kill(error);721722// Or use an `AbortSignal`723const controller = new AbortController();724await $({signal: controller.signal})`node long-script.js`;
23 unmodified lines
748echo $!749```750751```js752// zx does not return `childProcess.pid`752// zx does not return `subprocess.pid`753```754755```js756// Execa
23 unmodified lines
780Execa's scripting API mostly consists of only two methods: [`` $`command` ``](../readme.md#command) and [`$(options)`](../readme.md#options).781782[No special binary](#main-binary) is recommended, no [global variable](#global-variables) is injected: scripts are regular Node.js files.783784Execa is a thin wrapper around the core Node.js [`child_process` module](https://nodejs.org/api/child_process.html). Unlike zx, it lets you use [any of its native features](#background-processes): [`pid`](#pid), [IPC](https://nodejs.org/api/child_process.html#subprocesssendmessage-sendhandle-options-callback), [`unref()`](https://nodejs.org/api/child_process.html#subprocessunref), [`detached`](https://nodejs.org/api/child_process.html#child_processspawncommand-args-options), [`uid`](https://nodejs.org/api/child_process.html#child_processspawncommand-args-options), [`gid`](https://nodejs.org/api/child_process.html#child_processspawncommand-args-options), [`cancelSignal`](https://nodejs.org/api/child_process.html#child_processspawncommand-args-options), etc.784Execa is a thin wrapper around the core Node.js [`child_process` module](https://nodejs.org/api/child_process.html). Unlike zx, it lets you use [any of its native features](#background-subprocesses): [`pid`](#pid), [IPC](https://nodejs.org/api/child_process.html#subprocesssendmessage-sendhandle-options-callback), [`unref()`](https://nodejs.org/api/child_process.html#subprocessunref), [`detached`](https://nodejs.org/api/child_process.html#child_processspawncommand-args-options), [`uid`](https://nodejs.org/api/child_process.html#child_processspawncommand-args-options), [`gid`](https://nodejs.org/api/child_process.html#child_processspawncommand-args-options), [`cancelSignal`](https://nodejs.org/api/child_process.html#child_processspawncommand-args-options), etc.785786### Modularity787788zx includes many builtin utilities: `fetch()`, `question()`, `sleep()`, `stdin()`, `retry()`, `spinner()`, `chalk`, `fs-extra`, `os`, `path`, `globby`, `yaml`, `minimist`, `which`, Markdown scripts, remote scripts.
7 unmodified lines
796Also, [local binaries](#local-binaries) can be directly executed without using `npx`.797798### Debugging799800Child processes can be hard to debug, which is why Execa includes a [`verbose` option](#verbose-mode).800Subprocesses can be hard to debug, which is why Execa includes a [`verbose` option](#verbose-mode).801802Also, Execa's error messages and [properties](#errors) are very detailed to make it clear to determine why a process failed. Error messages and stack traces can be set with [`childProcess.kill(error)`](../readme.md#killerror).802Also, Execa's error messages and [properties](#errors) are very detailed to make it clear to determine why a subprocess failed. Error messages and stack traces can be set with [`subprocess.kill(error)`](../readme.md#killerror).803804Finally, unlike Bash and zx, which are stateful (options, current directory, etc.), Execa is [purely functional](#current-directory), which also helps with debugging.
modified:docs/transform.md+2 added-2 removed
modified:lib/exit/cleanup.js+2 added-2 removed
modified:lib/exit/code.js+2 added-2 removed
modified:lib/exit/kill.js+6 added-6 removed
18 unmodified lines
19};2021const DEFAULT_FORCE_KILL_TIMEOUT = 1000 * 5;2223// Monkey-patches `childProcess.kill()` to add `forceKillAfterDelay` behavior and `.kill(error)`24export const spawnedKill = ({kill, spawned, options: {forceKillAfterDelay, killSignal}, controller}, signalOrError, errorArgument) => {23// Monkey-patches `subprocess.kill()` to add `forceKillAfterDelay` behavior and `.kill(error)`24export const subprocessKill = ({kill, subprocess, options: {forceKillAfterDelay, killSignal}, controller}, signalOrError, errorArgument) => {25 const {signal, error} = parseKillArguments(signalOrError, errorArgument, killSignal);26 emitKillError(spawned, error);26 emitKillError(subprocess, error);27 const killResult = kill(signal);28 setKillTimeout({kill, signal, forceKillAfterDelay, killSignal, killResult, controller});29 return killResult;30};
13 unmodified lines
4445 return {signal, error};46};4748const emitKillError = (spawned, error) => {48const emitKillError = (subprocess, error) => {49 if (error !== undefined) {50 spawned.emit(errorSignal, error);50 subprocess.emit(errorSignal, error);51 }52};5354// Like `error` signal but internal to Execa.55// E.g. does not make process crash when no `error` listener is set.55// E.g. does not make subprocess crash when no `error` listener is set.56export const errorSignal = Symbol('error');5758const setKillTimeout = async ({kill, signal, forceKillAfterDelay, killSignal, killResult, controller}) => {59 if (!shouldForceKill(signal, forceKillAfterDelay, killSignal, killResult)) {
17 unmodified lines
modified:lib/exit/timeout.js+4 added-4 removed
modified:lib/pipe/sequence.js+6 added-6 removed
1// Like Bash, we await both processes. This is unlike some other shells which only await the destination process.2// Like Bash with the `pipefail` option, if either process fails, the whole pipe fails.3// Like Bash, if both processes fail, we return the failure of the destination.4// This ensures both processes' errors are present, using `error.pipedFrom`.5export const waitForBothProcesses = async processPromises => {1// Like Bash, we await both subprocesses. This is unlike some other shells which only await the destination subprocess.2// Like Bash with the `pipefail` option, if either subprocess fails, the whole pipe fails.3// Like Bash, if both subprocesses fail, we return the failure of the destination.4// This ensures both subprocesses' errors are present, using `error.pipedFrom`.5export const waitForBothSubprocesses = async subprocessPromises => {6 const [7 {status: sourceStatus, reason: sourceReason, value: sourceResult = sourceReason},8 {status: destinationStatus, reason: destinationReason, value: destinationResult = destinationReason},9 ] = await processPromises;9 ] = await subprocessPromises;1011 if (!destinationResult.pipedFrom.includes(sourceResult)) {12 destinationResult.pipedFrom.push(sourceResult);13 }
11 unmodified lines
modified:lib/pipe/setup.js+11 added-11 removed
1import isPlainObject from 'is-plain-obj';2import {normalizePipeArguments} from './validate.js';3import {handlePipeArgumentsError} from './throw.js';4import {waitForBothProcesses} from './sequence.js';5import {pipeProcessStream} from './streaming.js';4import {waitForBothSubprocesses} from './sequence.js';5import {pipeSubprocessStream} from './streaming.js';6import {unpipeOnAbort} from './abort.js';78// Pipe a process' `stdout`/`stderr`/`stdio` into another process' `stdin`9export const pipeToProcess = (sourceInfo, ...args) => {8// Pipe a subprocess' `stdout`/`stderr`/`stdio` into another subprocess' `stdin`9export const pipeToSubprocess = (sourceInfo, ...args) => {10 if (isPlainObject(args[0])) {11 return pipeToProcess.bind(undefined, {11 return pipeToSubprocess.bind(undefined, {12 ...sourceInfo,13 destinationOptions: {...sourceInfo.destinationOptions, ...args[0]},14 });15 }1617 const {destination, ...normalizedInfo} = normalizePipeArguments(sourceInfo, ...args);18 const promise = handlePipePromise({...normalizedInfo, destination});19 promise.pipe = pipeToProcess.bind(undefined, {...sourceInfo, source: destination, sourcePromise: promise, destinationOptions: {}});19 promise.pipe = pipeToSubprocess.bind(undefined, {...sourceInfo, source: destination, sourcePromise: promise, destinationOptions: {}});20 return promise;21};2223const handlePipePromise = async ({
7 unmodified lines
31 unpipeSignal,32 stdioStreamsGroups,33 startTime,34}) => {35 const processPromises = getProcessPromises(sourcePromise, destination);35 const subprocessPromises = getSubprocessPromises(sourcePromise, destination);36 handlePipeArgumentsError({37 sourceStream,38 sourceError,39 destinationStream,
3 unmodified lines
43 startTime,44 });45 const maxListenersController = new AbortController();46 try {47 const mergedStream = pipeProcessStream(sourceStream, destinationStream, maxListenersController);47 const mergedStream = pipeSubprocessStream(sourceStream, destinationStream, maxListenersController);48 return await Promise.race([49 waitForBothProcesses(processPromises),49 waitForBothSubprocesses(subprocessPromises),50 ...unpipeOnAbort(unpipeSignal, {sourceStream, mergedStream, sourceOptions, stdioStreamsGroups, startTime}),51 ]);52 } finally {53 maxListenersController.abort();54 }55};5657// `.pipe()` awaits the child process promises.57// `.pipe()` awaits the subprocess promises.58// When invalid arguments are passed to `.pipe()`, we throw an error, which prevents awaiting them.59// We need to ensure this does not create unhandled rejections.60const getProcessPromises = (sourcePromise, destination) => Promise.allSettled([sourcePromise, destination]);60const getSubprocessPromises = (sourcePromise, destination) => Promise.allSettled([sourcePromise, destination]);
modified:lib/pipe/streaming.js+8 added-8 removed
2 unmodified lines
3import {incrementMaxListeners} from '../utils.js';4import {pipeStreams} from '../stdio/pipeline.js';56// The piping behavior is like Bash.7// In particular, when one process exits, the other is not terminated by a signal.7// In particular, when one subprocess exits, the other is not terminated by a signal.8// Instead, its stdout (for the source) or stdin (for the destination) closes.9// If the process uses it, it will make it error with SIGPIPE or EPIPE (for the source) or end (for the destination).9// If the subprocess uses it, it will make it error with SIGPIPE or EPIPE (for the source) or end (for the destination).10// If it does not use it, it will continue running.11// This allows for processes to gracefully exit and lower the coupling between processes.12export const pipeProcessStream = (sourceStream, destinationStream, maxListenersController) => {11// This allows for subprocesses to gracefully exit and lower the coupling between subprocesses.12export const pipeSubprocessStream = (sourceStream, destinationStream, maxListenersController) => {13 const mergedStream = MERGED_STREAMS.has(destinationStream)14 ? pipeMoreProcessStream(sourceStream, destinationStream)15 : pipeFirstProcessStream(sourceStream, destinationStream);14 ? pipeMoreSubprocessStream(sourceStream, destinationStream)15 : pipeFirstSubprocessStream(sourceStream, destinationStream);16 incrementMaxListeners(sourceStream, SOURCE_LISTENERS_PER_PIPE, maxListenersController.signal);17 incrementMaxListeners(destinationStream, DESTINATION_LISTENERS_PER_PIPE, maxListenersController.signal);18 cleanupMergedStreamsMap(destinationStream);19 return mergedStream;20};2122// We use `merge-streams` to allow for multiple sources to pipe to the same destination.23const pipeFirstProcessStream = (sourceStream, destinationStream) => {23const pipeFirstSubprocessStream = (sourceStream, destinationStream) => {24 const mergedStream = mergeStreams([sourceStream]);25 pipeStreams(mergedStream, destinationStream);26 MERGED_STREAMS.set(destinationStream, mergedStream);27 return mergedStream;28};2930const pipeMoreProcessStream = (sourceStream, destinationStream) => {30const pipeMoreSubprocessStream = (sourceStream, destinationStream) => {31 const mergedStream = MERGED_STREAMS.get(destinationStream);32 mergedStream.add(sourceStream);33 return mergedStream;34};
17 unmodified lines
modified:lib/pipe/validate.js+10 added-10 removed
4 unmodified lines
5import {getStartTime} from '../return/duration.js';67export const normalizePipeArguments = ({source, sourcePromise, stdioStreamsGroups, destinationOptions}, ...args) => {8 const startTime = getStartTime();9 const sourceOptions = PROCESS_OPTIONS.get(source);9 const sourceOptions = SUBPROCESS_OPTIONS.get(source);10 const {11 destination,12 destinationStream,13 destinationError,
18 unmodified lines
32 try {33 const {destination, pipeOptions} = getDestination(destinationOptions, ...args);34 const destinationStream = destination.stdin;35 if (destinationStream === null) {36 throw new TypeError('The destination child process\'s stdin must be available. Please set its "stdin" option to "pipe".');36 throw new TypeError('The destination subprocess\'s stdin must be available. Please set its "stdin" option to "pipe".');37 }3839 return {destination, destinationStream, pipeOptions};40 } catch (error) {
2 unmodified lines
43};4445const getDestination = (destinationOptions, firstArgument, ...args) => {46 if (Array.isArray(firstArgument)) {47 const destination = create$({...destinationOptions, ...PIPED_PROCESS_OPTIONS})(firstArgument, ...args);47 const destination = create$({...destinationOptions, ...PIPED_SUBPROCESS_OPTIONS})(firstArgument, ...args);48 return {destination, pipeOptions: destinationOptions};49 }5051 if (typeof firstArgument === 'string' || firstArgument instanceof URL) {
1 unmodified line
53 throw new TypeError('Please use .pipe("file", ..., options) or .pipe(execa("file", ..., options)) instead of .pipe(options)(execa("file", ...)).');54 }5556 const [rawFile, rawArgs, rawOptions] = normalizeArguments(firstArgument, ...args);57 const destination = execa(rawFile, rawArgs, {...rawOptions, ...PIPED_PROCESS_OPTIONS});57 const destination = execa(rawFile, rawArgs, {...rawOptions, ...PIPED_SUBPROCESS_OPTIONS});58 return {destination, pipeOptions: rawOptions};59 }6061 if (PROCESS_OPTIONS.has(firstArgument)) {61 if (SUBPROCESS_OPTIONS.has(firstArgument)) {62 if (Object.keys(destinationOptions).length > 0) {63 throw new TypeError('Please use .pipe(options)`command` or .pipe($(options)`command`) instead of .pipe(options)($`command`).');64 }6566 return {destination: firstArgument, pipeOptions: args[0]};67 }6869 throw new TypeError(`The first argument must be a template string, an options object, or an Execa child process: ${firstArgument}`);69 throw new TypeError(`The first argument must be a template string, an options object, or an Execa subprocess: ${firstArgument}`);70};7172const PIPED_PROCESS_OPTIONS = {stdin: 'pipe', piped: true};72const PIPED_SUBPROCESS_OPTIONS = {stdin: 'pipe', piped: true};7374export const PROCESS_OPTIONS = new WeakMap();74export const SUBPROCESS_OPTIONS = new WeakMap();7576const getSourceStream = (source, stdioStreamsGroups, from, sourceOptions) => {77 try {78 const fdNumber = getFdNumber(stdioStreamsGroups, from);
42 unmodified lines
121};122123const getInvalidStdioOptionMessage = (fdNumber, from, sourceOptions) => {124 if (fdNumber === 'all' && !sourceOptions.all) {125 return 'The "all" option must be true to use `childProcess.pipe(destinationProcess, {from: "all"})`.';125 return 'The "all" option must be true to use `subprocess.pipe(destinationSubprocess, {from: "all"})`.';126 }127128 const {optionName, optionValue} = getInvalidStdioOption(fdNumber, sourceOptions);129 const pipeOptions = from === undefined ? '' : `, {from: ${serializeOptionValue(from)}}`;130 return `The \`${optionName}: ${serializeOptionValue(optionValue)}\` option is incompatible with using \`childProcess.pipe(destinationProcess${pipeOptions})\`.130 return `The \`${optionName}: ${serializeOptionValue(optionValue)}\` option is incompatible with using \`subprocess.pipe(destinationSubprocess${pipeOptions})\`.131Please set this option with "pipe" instead.`;132};133134const getInvalidStdioOption = (fdNumber, {stdout, stderr, stdio}) => {
20 unmodified lines
modified:lib/return/early-error.js+7 added-7 removed
2 unmodified lines
3import {cleanupStdioStreams} from '../stdio/async.js';4import {makeEarlyError} from './error.js';5import {handleResult} from './output.js';67// When the child process fails to spawn.8// We ensure the returned error is always both a promise and a child process.7// When the subprocess fails to spawn.8// We ensure the returned error is always both a promise and a subprocess.9export const handleEarlyError = ({error, command, escapedCommand, stdioStreamsGroups, options, startTime, verboseInfo}) => {10 cleanupStdioStreams(stdioStreamsGroups);1112 const spawned = new ChildProcess();13 createDummyStreams(spawned);12 const subprocess = new ChildProcess();13 createDummyStreams(subprocess);1415 const earlyError = makeEarlyError({error, command, escapedCommand, stdioStreamsGroups, options, startTime});16 const promise = handleDummyPromise(earlyError, verboseInfo, options);17 return {spawned, promise};17 return {subprocess, promise};18};1920const createDummyStreams = spawned => {20const createDummyStreams = subprocess => {21 const stdin = createDummyStream();22 const stdout = createDummyStream();23 const stderr = createDummyStream();24 const all = createDummyStream();25 const stdio = [stdin, stdout, stderr];26 Object.assign(spawned, {stdin, stdout, stderr, all, stdio});26 Object.assign(subprocess, {stdin, stdout, stderr, all, stdio});27};2829const createDummyStream = () => {30 const stream = new PassThrough();
5 unmodified lines
modified:lib/return/error.js+1 added-1 removed
112 unmodified lines
113114// Indicates that the error is used only to interrupt control flow, but not in the return value115export class DiscardedError extends Error {}116117// `signal` and `exitCode` emitted on `spawned.on('exit')` event can be `null`.117// `signal` and `exitCode` emitted on `subprocess.on('exit')` event can be `null`.118// We normalize them to `undefined`119const normalizeExitPayload = (rawExitCode, rawSignal) => {120 const exitCode = rawExitCode === null ? undefined : rawExitCode;121 const signal = rawSignal === null ? undefined : rawSignal;
78 unmodified lines
modified:lib/stdio/async.js+12 added-12 removed
35 unmodified lines
36};3738// Handle `input`, `inputFile`, `stdin`, `stdout` and `stderr` options, after spawning, in async mode39// When multiple input streams are used, we merge them to ensure the output stream ends only once each input stream has ended40export const pipeOutputAsync = (spawned, stdioStreamsGroups, stdioState, controller) => {41 stdioState.spawned = spawned;40export const pipeOutputAsync = (subprocess, stdioStreamsGroups, stdioState, controller) => {41 stdioState.subprocess = subprocess;42 const inputStreamsGroups = {};4344 for (const stdioStreams of stdioStreamsGroups) {45 for (const generatorStream of stdioStreams.filter(({type}) => type === 'generator')) {46 pipeGenerator(spawned, generatorStream);46 pipeGenerator(subprocess, generatorStream);47 }4849 for (const nonGeneratorStream of stdioStreams.filter(({type}) => type !== 'generator')) {50 pipeStdioOption(spawned, nonGeneratorStream, inputStreamsGroups, controller);50 pipeStdioOption(subprocess, nonGeneratorStream, inputStreamsGroups, controller);51 }52 }5354 for (const [fdNumber, inputStreams] of Object.entries(inputStreamsGroups)) {55 const inputStream = inputStreams.length === 1 ? inputStreams[0] : mergeStreams(inputStreams);56 pipeStreams(inputStream, spawned.stdio[fdNumber]);56 pipeStreams(inputStream, subprocess.stdio[fdNumber]);57 }58};5960const pipeStdioOption = (spawned, {type, value, direction, fdNumber}, inputStreamsGroups, controller) => {60const pipeStdioOption = (subprocess, {type, value, direction, fdNumber}, inputStreamsGroups, controller) => {61 if (type === 'native') {62 return;63 }6465 setStandardStreamMaxListeners(value, controller);6667 if (direction === 'output') {68 pipeStreams(spawned.stdio[fdNumber], value);68 pipeStreams(subprocess.stdio[fdNumber], value);69 } else {70 inputStreamsGroups[fdNumber] = [...(inputStreamsGroups[fdNumber] ?? []), value];71 }72};7374// Multiple processes might be piping from/to `process.std*` at the same time.74// Multiple subprocesses might be piping from/to `process.std*` at the same time.75// This is not necessarily an error and should not print a `maxListeners` warning.76const setStandardStreamMaxListeners = (stream, {signal}) => {77 if (isStandardStream(stream)) {78 incrementMaxListeners(stream, MAX_LISTENERS_INCREMENT, signal);
4 unmodified lines
83// If `stdin` option is an array, the values might be combined with `merge-streams`.84// That library also listens for `source` end, which adds 1 more listener.85const MAX_LISTENERS_INCREMENT = 2;8687// The stream error handling is performed by the piping logic above, which cannot be performed before process spawning.88// If the process spawning fails (e.g. due to an invalid command), the streams need to be manually destroyed.89// We need to create those streams before process spawning, in case their creation fails, e.g. when passing an invalid generator as argument.90// Like this, an exception would be thrown, which would prevent spawning a process.87// The stream error handling is performed by the piping logic above, which cannot be performed before subprocess spawning.88// If the subprocess spawning fails (e.g. due to an invalid command), the streams need to be manually destroyed.89// We need to create those streams before subprocess spawning, in case their creation fails, e.g. when passing an invalid generator as argument.90// Like this, an exception would be thrown, which would prevent spawning a subprocess.91export const cleanupStdioStreams = stdioStreamsGroups => {92 for (const {value, type} of stdioStreamsGroups.flat()) {93 if (type !== 'native' && !isStandardStream(value)) {94 value.destroy();
3 unmodified lines
modified:lib/stdio/encoding-transform.js+2 added-2 removed
3 unmodified lines
4/*5When using generators, add an internal generator that converts chunks from `Buffer` to `string` or `Uint8Array`.6This allows generator functions to operate with those types instead.7Chunks might be Buffer, Uint8Array or strings since:8- `childProcess.stdout|stderr` emits Buffers9- `childProcess.stdin.write()` accepts Buffer, Uint8Array or string8- `subprocess.stdout|stderr` emits Buffers9- `subprocess.stdin.write()` accepts Buffer, Uint8Array or string10- Previous generators might return Uint8Array or string1112However, those are converted to Buffer:13- on writes: `Duplex.writable` `decodeStrings: true` default option
36 unmodified lines
modified:lib/stdio/forward.js+4 added-4 removed
1// When the `std*: Iterable | WebStream | URL | filePath`, `input` or `inputFile` option is used, we pipe to `childProcess.std*`.2// When the `std*: Array` option is used, we emulate some of the native values ('inherit', Node.js stream and file descriptor integer). To do so, we also need to pipe to `childProcess.std*`.3// Therefore the `std*` options must be either `pipe` or `overlapped`. Other values do not set `childProcess.std*`.1// When the `std*: Iterable | WebStream | URL | filePath`, `input` or `inputFile` option is used, we pipe to `subprocess.std*`.2// When the `std*: Array` option is used, we emulate some of the native values ('inherit', Node.js stream and file descriptor integer). To do so, we also need to pipe to `subprocess.std*`.3// Therefore the `std*` options must be either `pipe` or `overlapped`. Other values do not set `subprocess.std*`.4export const forwardStdio = stdioStreamsGroups => stdioStreamsGroups.map(stdioStreams => forwardStdioItem(stdioStreams));56// Whether `childProcess.std*` will be set6// Whether `subprocess.std*` will be set7export const willPipeStreams = stdioStreams => PIPED_STDIO_VALUES.has(forwardStdioItem(stdioStreams));89export const PIPED_STDIO_VALUES = new Set(['pipe', 'overlapped', undefined, null]);10
8 unmodified lines
modified:lib/stdio/generator.js+10 added-10 removed
27 unmodified lines
2829/*30`objectMode` determines the return value's type, i.e. the `readableObjectMode`.31The chunk argument's type is based on the previous generator's return value, i.e. the `writableObjectMode` is based on the previous `readableObjectMode`.32The last input's generator is read by `childProcess.stdin` which:32The last input's generator is read by `subprocess.stdin` which:33- should not be in `objectMode` for performance reasons.34- can only be strings, Buffers and Uint8Arrays.35Therefore its `readableObjectMode` must be `false`.36The same applies to the first output's generator's `writableObjectMode`.
25 unmodified lines
62- Filtering, by using no `yield`6364Therefore, there is no need to allow Node.js or web transform streams.6566The `highWaterMark` is kept as the default value, since this is what `childProcess.std*` uses.66The `highWaterMark` is kept as the default value, since this is what `subprocess.std*` uses.6768Chunks are currently processed serially. We could add a `concurrency` option to parallelize in the future.69*/70export const generatorToDuplexStream = ({
12 unmodified lines
83 const duplexStream = generatorsToTransform(generators, {transformAsync, finalAsync, writableObjectMode, readableObjectMode});84 return {value: duplexStream};85};8687// `childProcess.stdin|stdout|stderr|stdio` is directly mutated.88export const pipeGenerator = (spawned, {value, direction, fdNumber}) => {87// `subprocess.stdin|stdout|stderr|stdio` is directly mutated.88export const pipeGenerator = (subprocess, {value, direction, fdNumber}) => {89 if (direction === 'output') {90 pipeStreams(spawned.stdio[fdNumber], value);90 pipeStreams(subprocess.stdio[fdNumber], value);91 } else {92 pipeStreams(value, spawned.stdio[fdNumber]);92 pipeStreams(value, subprocess.stdio[fdNumber]);93 }9495 const streamProperty = PROCESS_STREAM_PROPERTIES[fdNumber];95 const streamProperty = SUBPROCESS_STREAM_PROPERTIES[fdNumber];96 if (streamProperty !== undefined) {97 spawned[streamProperty] = value;97 subprocess[streamProperty] = value;98 }99100 spawned.stdio[fdNumber] = value;100 subprocess.stdio[fdNumber] = value;101};102103const PROCESS_STREAM_PROPERTIES = ['stdin', 'stdout', 'stderr'];103const SUBPROCESS_STREAM_PROPERTIES = ['stdin', 'stdout', 'stderr'];
modified:lib/stdio/lines.js+1 added-1 removed
1import {isUint8Array} from '../utils.js';2import {willPipeStreams} from './forward.js';34// Split chunks line-wise for streams exposed to users like `childProcess.stdout`.4// Split chunks line-wise for streams exposed to users like `subprocess.stdout`.5// Appending a noop transform in object mode is enough to do this, since every non-binary transform iterates line-wise.6export const handleStreamsLines = (stdioStreams, {lines}, isSync) => shouldSplitLines(stdioStreams, lines, isSync)7 ? [8 ...stdioStreams,
92 unmodified lines
modified:lib/stdio/transform.js+1 added-1 removed
70 unmodified lines
71 yield * transformChunk(finalChunk, generators, index + 1);72 }73};7475// Cancel any ongoing async generator when the Transform is destroyed, e.g. when the process errors75// Cancel any ongoing async generator when the Transform is destroyed, e.g. when the subprocess errors76const destroyTransform = callbackify(async ({currentIterable}, error) => {77 if (currentIterable !== undefined) {78 await (error ? currentIterable.throw(error) : currentIterable.return());79 return;
48 unmodified lines
modified:lib/stream/all.js+6 added-6 removed
1import mergeStreams from '@sindresorhus/merge-streams';2import {generatorToDuplexStream} from '../stdio/generator.js';3import {waitForChildStream} from './child.js';3import {waitForSubprocessStream} from './subprocess.js';45// `all` interleaves `stdout` and `stderr`6export const makeAllStream = ({stdout, stderr}, {all}) => all && (stdout || stderr)7 ? mergeStreams([stdout, stderr].filter(Boolean))8 : undefined;910// Read the contents of `childProcess.all` and|or wait for its completion11export const waitForAllStream = ({spawned, encoding, buffer, maxBuffer, streamInfo}) => waitForChildStream({12 stream: getAllStream(spawned, encoding),13 spawned,10// Read the contents of `subprocess.all` and|or wait for its completion11export const waitForAllStream = ({subprocess, encoding, buffer, maxBuffer, streamInfo}) => waitForSubprocessStream({12 stream: getAllStream(subprocess, encoding),13 subprocess,14 fdNumber: 1,15 encoding,16 buffer,17 maxBuffer: maxBuffer * 2,18 streamInfo,19});2021// When `childProcess.stdout` is in objectMode but not `childProcess.stderr` (or the opposite), we need to use both:21// When `subprocess.stdout` is in objectMode but not `subprocess.stderr` (or the opposite), we need to use both:22// - `getStreamAsArray()` for the chunks in objectMode, to return as an array without changing each chunk23// - `getStreamAsArrayBuffer()` or `getStream()` for the chunks not in objectMode, to convert them from Buffers to string or Uint8Array24// We do this by emulating the Buffer -> string|Uint8Array conversion performed by `get-stream` with our own, which is identical.25const getAllStream = ({all, stdout, stderr}, encoding) => all && stdout && stderr && stdout.readableObjectMode !== stderr.readableObjectMode
11 unmodified lines
deleted:lib/stream/child.js-70 removed
1import {setImmediate} from 'node:timers/promises';2import getStream, {getStreamAsArrayBuffer, getStreamAsArray, MaxBufferError} from 'get-stream';3import {waitForStream, handleStreamError, isInputFileDescriptor} from './wait.js';45export const waitForChildStream = async ({stream, spawned, fdNumber, encoding, buffer, maxBuffer, streamInfo}) => {6 if (!stream) {7 return;8 }910 if (isInputFileDescriptor(fdNumber, streamInfo.stdioStreamsGroups)) {11 await waitForStream(stream, fdNumber, streamInfo);12 return;13 }1415 if (!buffer) {16 await Promise.all([17 waitForStream(stream, fdNumber, streamInfo),18 resumeStream(stream),19 ]);20 return;21 }2223 try {24 return await getAnyStream(stream, encoding, maxBuffer);25 } catch (error) {26 if (error instanceof MaxBufferError) {27 spawned.kill();28 }2930 handleStreamError(error, fdNumber, streamInfo);31 return handleBufferedData(error, encoding);32 }33};3435// When using `buffer: false`, users need to read `childProcess.stdout|stderr|all` right away36// See https://github.com/sindresorhus/execa/issues/730 and https://github.com/sindresorhus/execa/pull/729#discussion_r146549631037const resumeStream = async stream => {38 await setImmediate();39 if (stream.readableFlowing === null) {40 stream.resume();41 }42};4344const getAnyStream = async (stream, encoding, maxBuffer) => {45 if (stream.readableObjectMode) {46 return getStreamAsArray(stream, {maxBuffer});47 }4849 const contents = encoding === 'buffer'50 ? await getStreamAsArrayBuffer(stream, {maxBuffer})51 : await getStream(stream, {maxBuffer});52 return applyEncoding(contents, encoding);53};5455// On failure, `result.stdout|stderr|all` should contain the currently buffered stream56// They are automatically closed and flushed by Node.js when the child process exits57// When `buffer` is `false`, `streamPromise` is `undefined` and there is no buffered data to retrieve58export const getBufferedData = async (streamPromise, encoding) => {59 try {60 return await streamPromise;61 } catch (error) {62 return handleBufferedData(error, encoding);63 }64};6566const handleBufferedData = (error, encoding) => error.bufferedData === undefined || Array.isArray(error.bufferedData)67 ? error.bufferedData68 : applyEncoding(error.bufferedData, encoding);6970const applyEncoding = (contents, encoding) => encoding === 'buffer' ? new Uint8Array(contents) : contents;
modified:lib/stream/exit.js+7 added-7 removed
5 unmodified lines
6// Since the `exit` event contains the signal name, we want to make sure we are listening for it.7// This function also takes into account the following unlikely cases:8// - `exit` being emitted in the same microtask as `spawn`9// - `error` being emitted multiple times10export const waitForExit = async spawned => {10export const waitForExit = async subprocess => {11 const [spawnPayload, exitPayload] = await Promise.allSettled([12 once(spawned, 'spawn'),13 once(spawned, 'exit'),12 once(subprocess, 'spawn'),13 once(subprocess, 'exit'),14 ]);1516 if (spawnPayload.status === 'rejected') {17 return [];18 }1920 return exitPayload.status === 'rejected'21 ? waitForProcessExit(spawned)21 ? waitForSubprocessExit(subprocess)22 : exitPayload.value;23};2425const waitForProcessExit = async spawned => {25const waitForSubprocessExit = async subprocess => {26 try {27 return await once(spawned, 'exit');27 return await once(subprocess, 'exit');28 } catch {29 return waitForProcessExit(spawned);29 return waitForSubprocessExit(subprocess);30 }31};
modified:lib/stream/resolve.js+22 added-22 removed
3 unmodified lines
4import {errorSignal} from '../exit/kill.js';5import {throwOnTimeout} from '../exit/timeout.js';6import {isStandardStream} from '../utils.js';7import {waitForAllStream} from './all.js';8import {waitForChildStream, getBufferedData} from './child.js';8import {waitForSubprocessStream, getBufferedData} from './subprocess.js';9import {waitForExit} from './exit.js';10import {waitForStream} from './wait.js';1112// Retrieve result of child process: exit code, signal, error, streams (stdout/stderr/all)13export const getSpawnedResult = async ({14 spawned,12// Retrieve result of subprocess: exit code, signal, error, streams (stdout/stderr/all)13export const getSubprocessResult = async ({14 subprocess,15 options: {encoding, buffer, maxBuffer, timeoutDuration: timeout},16 context,17 stdioStreamsGroups,18 originalStreams,19 controller,20}) => {21 const exitPromise = waitForExit(spawned);21 const exitPromise = waitForExit(subprocess);22 const streamInfo = {originalStreams, stdioStreamsGroups, exitPromise, propagating: new Set([])};2324 const stdioPromises = waitForChildStreams({spawned, encoding, buffer, maxBuffer, streamInfo});25 const allPromise = waitForAllStream({spawned, encoding, buffer, maxBuffer, streamInfo});26 const originalPromises = waitForOriginalStreams(originalStreams, spawned, streamInfo);24 const stdioPromises = waitForSubprocessStreams({subprocess, encoding, buffer, maxBuffer, streamInfo});25 const allPromise = waitForAllStream({subprocess, encoding, buffer, maxBuffer, streamInfo});26 const originalPromises = waitForOriginalStreams(originalStreams, subprocess, streamInfo);27 const customStreamsEndPromises = waitForCustomStreamsEnd(stdioStreamsGroups, streamInfo);2829 try {30 return await Promise.race([
4 unmodified lines
35 allPromise,36 ...originalPromises,37 ...customStreamsEndPromises,38 ]),39 throwOnProcessError(spawned, controller),40 throwOnInternalError(spawned, controller),41 ...throwOnTimeout(spawned, timeout, context, controller),39 throwOnSubprocessError(subprocess, controller),40 throwOnInternalError(subprocess, controller),41 ...throwOnTimeout(subprocess, timeout, context, controller),42 ]);43 } catch (error) {44 return Promise.all([45 {error},
5 unmodified lines
51 ]);52 }53};5455// Read the contents of `childProcess.std*` and|or wait for its completion56const waitForChildStreams = ({spawned, encoding, buffer, maxBuffer, streamInfo}) =>57 spawned.stdio.map((stream, fdNumber) => waitForChildStream({stream, spawned, fdNumber, encoding, buffer, maxBuffer, streamInfo}));55// Read the contents of `subprocess.std*` and|or wait for its completion56const waitForSubprocessStreams = ({subprocess, encoding, buffer, maxBuffer, streamInfo}) =>57 subprocess.stdio.map((stream, fdNumber) => waitForSubprocessStream({stream, subprocess, fdNumber, encoding, buffer, maxBuffer, streamInfo}));5859// Transforms replace `childProcess.std*`, which means they are not exposed to users.59// Transforms replace `subprocess.std*`, which means they are not exposed to users.60// However, we still want to wait for their completion.61const waitForOriginalStreams = (originalStreams, spawned, streamInfo) =>62 originalStreams.map((stream, fdNumber) => stream === spawned.stdio[fdNumber]61const waitForOriginalStreams = (originalStreams, subprocess, streamInfo) =>62 originalStreams.map((stream, fdNumber) => stream === subprocess.stdio[fdNumber]63 ? undefined64 : waitForStream(stream, fdNumber, streamInfo));6566// Some `stdin`/`stdout`/`stderr` options create a stream, e.g. when passing a file path.67// The `.pipe()` method automatically ends that stream when `childProcess` ends.67// The `.pipe()` method automatically ends that stream when `subprocess` ends.68// This makes sure we wait for the completion of those streams, in order to catch any error.69const waitForCustomStreamsEnd = (stdioStreamsGroups, streamInfo) => stdioStreamsGroups.flat()70 .filter(({value}) => isStream(value, {checkOpen: false}) && !isStandardStream(value))71 .map(({type, value, fdNumber}) => waitForStream(value, fdNumber, streamInfo, {72 isSameDirection: type === 'generator',73 stopOnExit: type === 'native',74 }));7576const throwOnProcessError = async (spawned, {signal}) => {77 const [error] = await once(spawned, 'error', {signal});76const throwOnSubprocessError = async (subprocess, {signal}) => {77 const [error] = await once(subprocess, 'error', {signal});78 throw error;79};8081const throwOnInternalError = async (spawned, {signal}) => {82 const [error] = await once(spawned, errorSignal, {signal});81const throwOnInternalError = async (subprocess, {signal}) => {82 const [error] = await once(subprocess, errorSignal, {signal});83 throw error;84};
added:lib/stream/subprocess.js+70 added
1import {setImmediate} from 'node:timers/promises';2import getStream, {getStreamAsArrayBuffer, getStreamAsArray, MaxBufferError} from 'get-stream';3import {waitForStream, handleStreamError, isInputFileDescriptor} from './wait.js';45export const waitForSubprocessStream = async ({stream, subprocess, fdNumber, encoding, buffer, maxBuffer, streamInfo}) => {6 if (!stream) {7 return;8 }910 if (isInputFileDescriptor(fdNumber, streamInfo.stdioStreamsGroups)) {11 await waitForStream(stream, fdNumber, streamInfo);12 return;13 }1415 if (!buffer) {16 await Promise.all([17 waitForStream(stream, fdNumber, streamInfo),18 resumeStream(stream),19 ]);20 return;21 }2223 try {24 return await getAnyStream(stream, encoding, maxBuffer);25 } catch (error) {26 if (error instanceof MaxBufferError) {27 subprocess.kill();28 }2930 handleStreamError(error, fdNumber, streamInfo);31 return handleBufferedData(error, encoding);32 }33};3435// When using `buffer: false`, users need to read `subprocess.stdout|stderr|all` right away36// See https://github.com/sindresorhus/execa/issues/730 and https://github.com/sindresorhus/execa/pull/729#discussion_r146549631037const resumeStream = async stream => {38 await setImmediate();39 if (stream.readableFlowing === null) {40 stream.resume();41 }42};4344const getAnyStream = async (stream, encoding, maxBuffer) => {45 if (stream.readableObjectMode) {46 return getStreamAsArray(stream, {maxBuffer});47 }4849 const contents = encoding === 'buffer'50 ? await getStreamAsArrayBuffer(stream, {maxBuffer})51 : await getStream(stream, {maxBuffer});52 return applyEncoding(contents, encoding);53};5455// On failure, `result.stdout|stderr|all` should contain the currently buffered stream56// They are automatically closed and flushed by Node.js when the subprocess exits57// When `buffer` is `false`, `streamPromise` is `undefined` and there is no buffered data to retrieve58export const getBufferedData = async (streamPromise, encoding) => {59 try {60 return await streamPromise;61 } catch (error) {62 return handleBufferedData(error, encoding);63 }64};6566const handleBufferedData = (error, encoding) => error.bufferedData === undefined || Array.isArray(error.bufferedData)67 ? error.bufferedData68 : applyEncoding(error.bufferedData, encoding);6970const applyEncoding = (contents, encoding) => encoding === 'buffer' ? new Uint8Array(contents) : contents;
modified:lib/stream/wait.js+6 added-6 removed
1import {finished} from 'node:stream/promises';23// Wraps `finished(stream)` to handle the following case:4// - When the child process exits, Node.js automatically calls `childProcess.stdin.destroy()`, which we need to ignore.5// - However, we still need to throw if `childProcess.stdin.destroy()` is called before child process exit.4// - When the subprocess exits, Node.js automatically calls `subprocess.stdin.destroy()`, which we need to ignore.5// - However, we still need to throw if `subprocess.stdin.destroy()` is called before subprocess exit.6export const waitForStream = async (stream, fdNumber, streamInfo, {isSameDirection, stopOnExit = false} = {}) => {7 const {originalStreams: [originalStdin], exitPromise} = streamInfo;89 const abortController = new AbortController();
31 unmodified lines
41 : isStreamAbort(error);42};4344// Unfortunately, we cannot use the stream's class or properties to know whether it is readable or writable.45// For example, `childProcess.stdin` is technically a Duplex, but can only be used as a writable.45// For example, `subprocess.stdin` is technically a Duplex, but can only be used as a writable.46// Therefore, we need to use the file descriptor's direction (`stdin` is input, `stdout` is output, etc.).47// However, while `childProcess.std*` and transforms follow that direction, any stream passed the `std*` option has the opposite direction.48// For example, `childProcess.stdin` is a writable, but the `stdin` option is a readable.47// However, while `subprocess.std*` and transforms follow that direction, any stream passed the `std*` option has the opposite direction.48// For example, `subprocess.stdin` is a writable, but the `stdin` option is a readable.49export const isInputFileDescriptor = (fdNumber, stdioStreamsGroups) => {50 const [{direction}] = stdioStreamsGroups.find(stdioStreams => stdioStreams[0].fdNumber === fdNumber);51 return direction === 'input';52};
3 unmodified lines
56// Therefore, we ignore this error on readable streams.57const isStreamAbort = error => error?.code === 'ERR_STREAM_PREMATURE_CLOSE';5859// When `stream.write()` is called but the underlying source has been closed, `EPIPE` is emitted.60// When piping processes, the source process usually decides when to stop piping.60// When piping subprocesses, the source subprocess usually decides when to stop piping.61// However, there are some instances when the destination does instead, such as `... | head -n1`.62// It notifies the source by using `EPIPE`.63// Therefore, we ignore this error on writable streams.64const isStreamEpipe = error => error?.code === 'EPIPE';
modified:lib/verbose/log.js+1 added-1 removed
23 unmodified lines
24].join(' ');2526const identity = string => string;2728// Prepending the timestamp allows debugging the slow paths of a process28// Prepending the timestamp allows debugging the slow paths of a subprocess29const getTimestamp = () => {30 const date = new Date();31 return `${padField(date.getHours(), 2)}:${padField(date.getMinutes(), 2)}:${padField(date.getSeconds(), 2)}.${padField(date.getMilliseconds(), 3)}`;32};
11 unmodified lines
modified:lib/verbose/output.js+4 added-4 removed
37 unmodified lines
38// We could print `stdio[3+]` but it often is redirected to files and streams, with the same issue.39// So we only print stdout and stderr.40const fdUsesVerbose = ([{fdNumber}]) => fdNumber === 1 || fdNumber === 2;4142const verboseGenerator = function * ({stdioState: {spawned: {stdio}}, fdNumber, verboseInfo}, line) {42const verboseGenerator = function * ({stdioState: {subprocess: {stdio}}, fdNumber, verboseInfo}, line) {43 if (!isPiping(stdio[fdNumber])) {44 logOutput(line, verboseInfo);45 }4647 yield line;48};4950// When `childProcess.stdout|stderr.pipe()` is called, `verbose` becomes a noop.50// When `subprocess.stdout|stderr.pipe()` is called, `verbose` becomes a noop.51// This prevents the following problems:52// - `.pipe()` achieves the same result as using `stdout: 'inherit'`, `stdout: stream`, etc. which also make `verbose` a noop.53// For example, `childProcess.stdout.pipe(process.stdin)` would print each line twice.54// - When chaining processes with `childProcess.pipe(otherProcess)`, only the last one should print its output.53// For example, `subprocess.stdout.pipe(process.stdin)` would print each line twice.54// - When chaining subprocesses with `subprocess.pipe(otherSubprocess)`, only the last one should print its output.55// Detecting whether `.pipe()` is impossible without monkey-patching it, so we use the following undocumented property.56// This is not a critical behavior since changes of the following property would only make `verbose` more verbose.57const isPiping = stream => stream._readableState.pipes.length > 0;58
10 unmodified lines
modified:lib/async.js+21 added-21 removed
3 unmodified lines
4import {makeError, makeSuccessResult} from './return/error.js';5import {handleOutput, handleResult} from './return/output.js';6import {handleEarlyError} from './return/early-error.js';7import {handleInputAsync, pipeOutputAsync} from './stdio/async.js';8import {spawnedKill} from './exit/kill.js';8import {subprocessKill} from './exit/kill.js';9import {cleanupOnExit} from './exit/cleanup.js';10import {pipeToProcess} from './pipe/setup.js';11import {PROCESS_OPTIONS} from './pipe/validate.js';10import {pipeToSubprocess} from './pipe/setup.js';11import {SUBPROCESS_OPTIONS} from './pipe/validate.js';12import {logEarlyResult} from './verbose/complete.js';13import {makeAllStream} from './stream/all.js';14import {getSpawnedResult} from './stream/resolve.js';14import {getSubprocessResult} from './stream/resolve.js';15import {mergePromise} from './promise.js';1617export const execa = (rawFile, rawArgs, rawOptions) => {18 const {file, args, command, escapedCommand, startTime, verboseInfo, options, stdioStreamsGroups, stdioState} = handleAsyncArguments(rawFile, rawArgs, rawOptions);19 const {spawned, promise} = spawnProcessAsync({file, args, options, startTime, verboseInfo, command, escapedCommand, stdioStreamsGroups, stdioState});20 spawned.pipe = pipeToProcess.bind(undefined, {source: spawned, sourcePromise: promise, stdioStreamsGroups, destinationOptions: {}});21 mergePromise(spawned, promise);22 PROCESS_OPTIONS.set(spawned, options);23 return spawned;19 const {subprocess, promise} = spawnSubprocessAsync({file, args, options, startTime, verboseInfo, command, escapedCommand, stdioStreamsGroups, stdioState});20 subprocess.pipe = pipeToSubprocess.bind(undefined, {source: subprocess, sourcePromise: promise, stdioStreamsGroups, destinationOptions: {}});21 mergePromise(subprocess, promise);22 SUBPROCESS_OPTIONS.set(subprocess, options);23 return subprocess;24};2526const handleAsyncArguments = (rawFile, rawArgs, rawOptions) => {27 [rawFile, rawArgs, rawOptions] = normalizeArguments(rawFile, rawArgs, rawOptions);
18 unmodified lines
4647 return {...options, timeoutDuration: timeout, signal: cancelSignal};48};4950const spawnProcessAsync = ({file, args, options, startTime, verboseInfo, command, escapedCommand, stdioStreamsGroups, stdioState}) => {51 let spawned;50const spawnSubprocessAsync = ({file, args, options, startTime, verboseInfo, command, escapedCommand, stdioStreamsGroups, stdioState}) => {51 let subprocess;52 try {53 spawned = spawn(file, args, options);53 subprocess = spawn(file, args, options);54 } catch (error) {55 return handleEarlyError({error, command, escapedCommand, stdioStreamsGroups, options, startTime, verboseInfo});56 }5758 const controller = new AbortController();59 setMaxListeners(Number.POSITIVE_INFINITY, controller.signal);6061 const originalStreams = [...spawned.stdio];62 pipeOutputAsync(spawned, stdioStreamsGroups, stdioState, controller);63 cleanupOnExit(spawned, options, controller);61 const originalStreams = [...subprocess.stdio];62 pipeOutputAsync(subprocess, stdioStreamsGroups, stdioState, controller);63 cleanupOnExit(subprocess, options, controller);6465 spawned.kill = spawnedKill.bind(undefined, {kill: spawned.kill.bind(spawned), spawned, options, controller});66 spawned.all = makeAllStream(spawned, options);65 subprocess.kill = subprocessKill.bind(undefined, {kill: subprocess.kill.bind(subprocess), subprocess, options, controller});66 subprocess.all = makeAllStream(subprocess, options);6768 const promise = handlePromise({spawned, options, startTime, verboseInfo, stdioStreamsGroups, originalStreams, command, escapedCommand, controller});69 return {spawned, promise};68 const promise = handlePromise({subprocess, options, startTime, verboseInfo, stdioStreamsGroups, originalStreams, command, escapedCommand, controller});69 return {subprocess, promise};70};7172const handlePromise = async ({spawned, options, startTime, verboseInfo, stdioStreamsGroups, originalStreams, command, escapedCommand, controller}) => {72const handlePromise = async ({subprocess, options, startTime, verboseInfo, stdioStreamsGroups, originalStreams, command, escapedCommand, controller}) => {73 const context = {timedOut: false};7475 const [76 errorInfo,77 [exitCode, signal],78 stdioResults,79 allResult,80 ] = await getSpawnedResult({spawned, options, context, stdioStreamsGroups, originalStreams, controller});80 ] = await getSubprocessResult({subprocess, options, context, stdioStreamsGroups, originalStreams, controller});81 controller.abort();8283 const stdio = stdioResults.map(stdioResult => handleOutput(options, stdioResult));84 const all = handleOutput(options, allResult);
19 unmodified lines
modified:lib/promise.js+3 added-3 removed
1// The return value is a mixin of `childProcess` and `Promise`2export const mergePromise = (spawned, promise) => {1// The return value is a mixin of `subprocess` and `Promise`2export const mergePromise = (subprocess, promise) => {3 for (const [property, descriptor] of descriptors) {4 const value = descriptor.value.bind(promise);5 Reflect.defineProperty(spawned, property, {...descriptor, value});5 Reflect.defineProperty(subprocess, property, {...descriptor, value});6 }7};89// eslint-disable-next-line unicorn/prefer-top-level-await
6 unmodified lines
modified:lib/script.js+2 added-2 removed
1import isPlainObject from 'is-plain-obj';2import {isBinary, binaryToString, isChildProcess} from './utils.js';2import {isBinary, binaryToString, isSubprocess} from './utils.js';3import {execa} from './async.js';4import {execaSync} from './sync.js';56export const create$ = options => {
138 unmodified lines
145146 if (147 typeOfExpression === 'object'148 && expression !== null149 && !isChildProcess(expression)149 && !isSubprocess(expression)150 && 'stdout' in expression151 ) {152 const typeOfStdout = typeof expression.stdout;153
23 unmodified lines
modified:lib/sync.js+2 added-2 removed
6 unmodified lines
7import {isFailedExit} from './exit/code.js';89export const execaSync = (rawFile, rawArgs, rawOptions) => {10 const {file, args, command, escapedCommand, startTime, verboseInfo, options, stdioStreamsGroups} = handleSyncArguments(rawFile, rawArgs, rawOptions);11 const result = spawnProcessSync({file, args, options, command, escapedCommand, stdioStreamsGroups, startTime});11 const result = spawnSubprocessSync({file, args, options, command, escapedCommand, stdioStreamsGroups, startTime});12 return handleResult(result, verboseInfo, options);13};1415const handleSyncArguments = (rawFile, rawArgs, rawOptions) => {
19 unmodified lines
35 throw new TypeError('The "ipc: true" option cannot be used with synchronous methods.');36 }37};3839const spawnProcessSync = ({file, args, options, command, escapedCommand, stdioStreamsGroups, startTime}) => {39const spawnSubprocessSync = ({file, args, options, command, escapedCommand, stdioStreamsGroups, startTime}) => {40 let syncResult;41 try {42 syncResult = spawnSync(file, args, options);43 } catch (error) {
24 unmodified lines
modified:lib/utils.js+1 added-1 removed
25 unmodified lines
26 eventEmitter.setMaxListeners(eventEmitter.getMaxListeners() - maxListenersIncrement);27 });28};2930export const isChildProcess = value => value instanceof ChildProcess;30export const isSubprocess = value => value instanceof ChildProcess;
modified:test/arguments/cwd.js+1 added-1 removed
45 unmodified lines
4647test('The "cwd" option defaults to process.cwd()', testErrorCwdDefault, execa);48test('The "cwd" option defaults to process.cwd() - sync', testErrorCwdDefault, execaSync);4950// Windows does not allow removing a directory used as `cwd` of a running process50// Windows does not allow removing a directory used as `cwd` of a running subprocess51if (!isWindows) {52 const testCwdPreSpawn = async (t, execaMethod) => {53 const currentCwd = process.cwd();54 const filePath = tempfile();
49 unmodified lines
modified:test/arguments/node.js+25 added-25 removed
97 unmodified lines
98test('The "execPath" option cannot be used - "node" option sync', testFormerNodePath, runWithNodeOptionSync);99100const nodePathArguments = ['-p', ['process.env.Path || process.env.PATH']];101102const testChildNodePath = async (t, execaMethod, mapPath) => {102const testSubprocessNodePath = async (t, execaMethod, mapPath) => {103 const nodePath = mapPath(await getNodePath());104 const {stdout} = await execaMethod(...nodePathArguments, {nodePath});105 t.true(stdout.includes(TEST_NODE_VERSION));106};107108test.serial('The "nodePath" option impacts the child process - execaNode()', testChildNodePath, execaNode, identity);109test.serial('The "nodePath" option impacts the child process - "node" option', testChildNodePath, runWithNodeOption, identity);110test.serial('The "nodePath" option impacts the child process - "node" option sync', testChildNodePath, runWithNodeOptionSync, identity);108test.serial('The "nodePath" option impacts the subprocess - execaNode()', testSubprocessNodePath, execaNode, identity);109test.serial('The "nodePath" option impacts the subprocess - "node" option', testSubprocessNodePath, runWithNodeOption, identity);110test.serial('The "nodePath" option impacts the subprocess - "node" option sync', testSubprocessNodePath, runWithNodeOptionSync, identity);111112const testChildNodePathDefault = async (t, execaMethod) => {112const testSubprocessNodePathDefault = async (t, execaMethod) => {113 const {stdout} = await execaMethod(...nodePathArguments);114 t.true(stdout.includes(dirname(process.execPath)));115};116117test('The "nodePath" option defaults to the current Node.js binary in the child process - execaNode()', testChildNodePathDefault, execaNode);118test('The "nodePath" option defaults to the current Node.js binary in the child process - "node" option', testChildNodePathDefault, runWithNodeOption);119test('The "nodePath" option defaults to the current Node.js binary in the child process - "node" option sync', testChildNodePathDefault, runWithNodeOptionSync);117test('The "nodePath" option defaults to the current Node.js binary in the subprocess - execaNode()', testSubprocessNodePathDefault, execaNode);118test('The "nodePath" option defaults to the current Node.js binary in the subprocess - "node" option', testSubprocessNodePathDefault, runWithNodeOption);119test('The "nodePath" option defaults to the current Node.js binary in the subprocess - "node" option sync', testSubprocessNodePathDefault, runWithNodeOptionSync);120121test.serial('The "nodePath" option requires "node: true" to impact the child process', async t => {121test.serial('The "nodePath" option requires "node: true" to impact the subprocess', async t => {122 const nodePath = await getNodePath();123 const {stdout} = await execa('node', nodePathArguments.flat(), {nodePath});124 t.false(stdout.includes(TEST_NODE_VERSION));125});126127const testChildNodePathCwd = async (t, execaMethod) => {127const testSubprocessNodePathCwd = async (t, execaMethod) => {128 const nodePath = await getNodePath();129 const cwd = dirname(dirname(nodePath));130 const relativeExecPath = relative(cwd, nodePath);131 const {stdout} = await execaMethod(...nodePathArguments, {nodePath: relativeExecPath, cwd});132 t.true(stdout.includes(TEST_NODE_VERSION));133};134135test.serial('The "nodePath" option is relative to "cwd" when used in the child process - execaNode()', testChildNodePathCwd, execaNode);136test.serial('The "nodePath" option is relative to "cwd" when used in the child process - "node" option', testChildNodePathCwd, runWithNodeOption);137test.serial('The "nodePath" option is relative to "cwd" when used in the child process - "node" option sync', testChildNodePathCwd, runWithNodeOptionSync);135test.serial('The "nodePath" option is relative to "cwd" when used in the subprocess - execaNode()', testSubprocessNodePathCwd, execaNode);136test.serial('The "nodePath" option is relative to "cwd" when used in the subprocess - "node" option', testSubprocessNodePathCwd, runWithNodeOption);137test.serial('The "nodePath" option is relative to "cwd" when used in the subprocess - "node" option sync', testSubprocessNodePathCwd, runWithNodeOptionSync);138139const testCwdNodePath = async (t, execaMethod) => {140 const nodePath = await getNodePath();141 const cwd = dirname(dirname(nodePath));
26 unmodified lines
168 t.is(stdout, foobarString);169 t.is(stdio[3], '');170};171172test('The "nodeOptions" option removes --inspect without a port when defined by parent process - execaNode()', testInspectRemoval, '--inspect', 'execaNode');173test('The "nodeOptions" option removes --inspect without a port when defined by parent process - "node" option', testInspectRemoval, '--inspect', 'nodeOption');174test('The "nodeOptions" option removes --inspect with a port when defined by parent process - execaNode()', testInspectRemoval, '--inspect=9222', 'execaNode');175test('The "nodeOptions" option removes --inspect with a port when defined by parent process - "node" option', testInspectRemoval, '--inspect=9222', 'nodeOption');176test('The "nodeOptions" option removes --inspect-brk without a port when defined by parent process - execaNode()', testInspectRemoval, '--inspect-brk', 'execaNode');177test('The "nodeOptions" option removes --inspect-brk without a port when defined by parent process - "node" option', testInspectRemoval, '--inspect-brk', 'nodeOption');178test('The "nodeOptions" option removes --inspect-brk with a port when defined by parent process - execaNode()', testInspectRemoval, '--inspect-brk=9223', 'execaNode');179test('The "nodeOptions" option removes --inspect-brk with a port when defined by parent process - "node" option', testInspectRemoval, '--inspect-brk=9223', 'nodeOption');172test('The "nodeOptions" option removes --inspect without a port when defined by current process - execaNode()', testInspectRemoval, '--inspect', 'execaNode');173test('The "nodeOptions" option removes --inspect without a port when defined by current process - "node" option', testInspectRemoval, '--inspect', 'nodeOption');174test('The "nodeOptions" option removes --inspect with a port when defined by current process - execaNode()', testInspectRemoval, '--inspect=9222', 'execaNode');175test('The "nodeOptions" option removes --inspect with a port when defined by current process - "node" option', testInspectRemoval, '--inspect=9222', 'nodeOption');176test('The "nodeOptions" option removes --inspect-brk without a port when defined by current process - execaNode()', testInspectRemoval, '--inspect-brk', 'execaNode');177test('The "nodeOptions" option removes --inspect-brk without a port when defined by current process - "node" option', testInspectRemoval, '--inspect-brk', 'nodeOption');178test('The "nodeOptions" option removes --inspect-brk with a port when defined by current process - execaNode()', testInspectRemoval, '--inspect-brk=9223', 'execaNode');179test('The "nodeOptions" option removes --inspect-brk with a port when defined by current process - "node" option', testInspectRemoval, '--inspect-brk=9223', 'nodeOption');180181const testInspectDifferentPort = async (t, execaMethod) => {182 const {stdout, stdio} = await spawnNestedExecaNode(['--inspect=9225'], '', execaMethod, '--inspect=9224');183 t.is(stdout, foobarString);184 t.true(stdio[3].includes('Debugger listening'));185};186187test.serial('The "nodeOptions" option allows --inspect with a different port even when defined by parent process - execaNode()', testInspectDifferentPort, 'execaNode');188test.serial('The "nodeOptions" option allows --inspect with a different port even when defined by parent process - "node" option', testInspectDifferentPort, 'nodeOption');187test.serial('The "nodeOptions" option allows --inspect with a different port even when defined by current process - execaNode()', testInspectDifferentPort, 'execaNode');188test.serial('The "nodeOptions" option allows --inspect with a different port even when defined by current process - "node" option', testInspectDifferentPort, 'nodeOption');189190const testInspectSamePort = async (t, execaMethod) => {191 const {stdout, stdio} = await spawnNestedExecaNode(['--inspect=9226'], '', execaMethod, '--inspect=9226');192 t.is(stdout, foobarString);193 t.true(stdio[3].includes('address already in use'));194};195196test.serial('The "nodeOptions" option forbids --inspect with the same port when defined by parent process - execaNode()', testInspectSamePort, 'execaNode');197test.serial('The "nodeOptions" option forbids --inspect with the same port when defined by parent process - "node" option', testInspectSamePort, 'nodeOption');196test.serial('The "nodeOptions" option forbids --inspect with the same port when defined by current process - execaNode()', testInspectSamePort, 'execaNode');197test.serial('The "nodeOptions" option forbids --inspect with the same port when defined by current process - "node" option', testInspectSamePort, 'nodeOption');198199const testIpc = async (t, execaMethod, options) => {200 const subprocess = execaMethod('send.js', [], options);201 await pEvent(subprocess, 'message');
57 unmodified lines
modified:test/exit/cancel.js+1 added-1 removed
67 unmodified lines
68 const {isCanceled} = await t.throwsAsync(subprocess);69 t.true(isCanceled);70});7172test('calling abort on a successfully completed process does not make result.isCanceled true', async t => {72test('calling abort on a successfully completed subprocess does not make result.isCanceled true', async t => {73 const abortController = new AbortController();74 const subprocess = execa('noop.js', {cancelSignal: abortController.signal});75 const result = await subprocess;76 abortController.abort();
9 unmodified lines
modified:test/exit/cleanup.js+6 added-6 removed
8 unmodified lines
9setFixtureDir();1011const isWindows = process.platform === 'win32';1213// When child process exits before parent process13// When subprocess exits before current process14const spawnAndExit = async (t, cleanup, detached) => {15 await t.notThrowsAsync(execa('nested.js', [JSON.stringify({cleanup, detached}), 'noop.js']));16};17
1 unmodified line
19test('spawnAndExit cleanup', spawnAndExit, true, false);20test('spawnAndExit detached', spawnAndExit, false, true);21test('spawnAndExit cleanup detached', spawnAndExit, true, true);2223// When parent process exits before child process23// When current process exits before subprocess24const spawnAndKill = async (t, [signal, cleanup, detached, isKilled]) => {25 const subprocess = execa('sub-process.js', [cleanup, detached], {stdio: 'ignore', ipc: true});25 const subprocess = execa('subprocess.js', [cleanup, detached], {stdio: 'ignore', ipc: true});2627 const pid = await pEvent(subprocess, 'message');28 t.true(Number.isInteger(pid));29 t.true(isRunning(pid));
5 unmodified lines
3536 if (isKilled) {37 await Promise.race([38 setTimeout(1e4, undefined, {ref: false}),39 pollForProcessExit(pid),39 pollForSubprocessExit(pid),40 ]);41 t.is(isRunning(pid), false);42 } else {43 t.is(isRunning(pid), true);44 process.kill(pid, 'SIGKILL');45 }46};4748const pollForProcessExit = async pid => {48const pollForSubprocessExit = async pid => {49 while (isRunning(pid)) {50 // eslint-disable-next-line no-await-in-loop51 await setTimeout(100);52 }
25 unmodified lines
78 await subprocess;79 t.false(exitListeners.includes(listener));80});8182test('detach child process', async t => {82test('detach subprocess', async t => {83 const {stdout} = await execa('detach.js');84 const pid = Number(stdout);85 t.true(Number.isInteger(pid));86 t.true(isRunning(pid));
3 unmodified lines
modified:test/exit/code.js+1 added-1 removed
72 unmodified lines
73 const {signal} = await execa('noop.js');74 t.is(signal, undefined);75});7677test('result.signal is undefined if process failed, but was not killed', async t => {77test('result.signal is undefined if subprocess failed, but was not killed', async t => {78 const {signal} = await t.throwsAsync(execa('fail.js'));79 t.is(signal, undefined);80});81
4 unmodified lines
modified:test/exit/kill.js+7 added-7 removed
44 unmodified lines
4546test('`forceKillAfterDelay` should not be NaN', testInvalidForceKill, Number.NaN);47test('`forceKillAfterDelay` should not be negative', testInvalidForceKill, -1);4849// `SIGTERM` cannot be caught on Windows, and it always aborts the process (like `SIGKILL` on Unix).49// `SIGTERM` cannot be caught on Windows, and it always aborts the subprocess (like `SIGKILL` on Unix).50// Therefore, this feature and those tests must be different on Windows.51if (isWindows) {52 test('Can call `.kill()` with `forceKillAfterDelay` on Windows', async t => {53 const {subprocess} = await spawnNoKillable(1);
160 unmodified lines
214 t.is(await t.throwsAsync(subprocess), error);215 t.is(error.signal, 'SIGINT');216});217218test('.kill(error) is a noop if process already exited', async t => {218test('.kill(error) is a noop if subprocess already exited', async t => {219 const subprocess = execa('empty.js');220 await subprocess;221 t.false(isRunning(subprocess.pid));222 t.false(subprocess.kill(new Error('test')));223});224225test('.kill(error) terminates but does not change the error if the process already errored but did not exit yet', async t => {225test('.kill(error) terminates but does not change the error if the subprocess already errored but did not exit yet', async t => {226 const subprocess = execa('forever.js');227 const error = new Error('first');228 subprocess.stdout.destroy(error);229 await setImmediate();
22 unmodified lines
252 subprocess.kill(error);253 t.is(await Promise.race([t.throwsAsync(subprocess), once(subprocess, 'error')]), error);254});255256test('child process errors are handled before spawn', async t => {256test('subprocess errors are handled before spawn', async t => {257 const subprocess = execa('forever.js');258 const error = new Error('test');259 subprocess.emit('error', error);260 subprocess.kill();
3 unmodified lines
264 t.is(thrownError.signal, undefined);265 t.false(thrownError.isTerminated);266});267268test('child process errors are handled after spawn', async t => {268test('subprocess errors are handled after spawn', async t => {269 const subprocess = execa('forever.js');270 await once(subprocess, 'spawn');271 const error = new Error('test');272 subprocess.emit('error', error);
4 unmodified lines
277 t.is(thrownError.signal, 'SIGTERM');278 t.true(thrownError.isTerminated);279});280281test('child process double errors are handled after spawn', async t => {281test('subprocess double errors are handled after spawn', async t => {282 const abortController = new AbortController();283 const subprocess = execa('forever.js', {cancelSignal: abortController.signal});284 await once(subprocess, 'spawn');285 const error = new Error('test');
6 unmodified lines
292 t.is(thrownError.signal, 'SIGTERM');293 t.true(thrownError.isTerminated);294});295296test('child process errors use killSignal', async t => {296test('subprocess errors use killSignal', async t => {297 const subprocess = execa('forever.js', {killSignal: 'SIGINT'});298 await once(subprocess, 'spawn');299 const error = new Error('test');300 subprocess.emit('error', error);
6 unmodified lines
modified:test/exit/timeout.js+6 added-6 removed
2 unmodified lines
3import {setFixtureDir, FIXTURES_DIR} from '../helpers/fixtures-dir.js';45setFixtureDir();67test('timeout kills the process if it times out', async t => {7test('timeout kills the subprocess if it times out', async t => {8 const {isTerminated, signal, timedOut, originalMessage, shortMessage, message} = await t.throwsAsync(execa('forever.js', {timeout: 1}));9 t.true(isTerminated);10 t.is(signal, 'SIGTERM');11 t.true(timedOut);
1 unmodified line
13 t.is(shortMessage, 'Command timed out after 1 milliseconds: forever.js');14 t.is(message, shortMessage);15});1617test('timeout kills the process if it times out, in sync mode', async t => {17test('timeout kills the subprocess if it times out, in sync mode', async t => {18 const {isTerminated, signal, timedOut, originalMessage, shortMessage, message} = await t.throws(() => {19 execaSync('node', ['forever.js'], {timeout: 1, cwd: FIXTURES_DIR});20 });21 t.true(isTerminated);
3 unmodified lines
25 t.is(shortMessage, `Command timed out after 1 milliseconds: node forever.js\n${originalMessage}`);26 t.is(message, shortMessage);27});2829test('timeout does not kill the process if it does not time out', async t => {29test('timeout does not kill the subprocess if it does not time out', async t => {30 const {timedOut} = await execa('delay.js', ['500'], {timeout: 1e8});31 t.false(timedOut);32});33
32 unmodified lines
66 t.false(timedOut);67});6869test('timedOut is true if the timeout happened after a different error occurred', async t => {70 const childProcess = execa('forever.js', {timeout: 1e3});70 const subprocess = execa('forever.js', {timeout: 1e3});71 const error = new Error('test');72 childProcess.emit('error', error);73 t.is(await t.throwsAsync(childProcess), error);72 subprocess.emit('error', error);73 t.is(await t.throwsAsync(subprocess), error);74 t.true(error.timedOut);75});
modified:test/fixtures/nested-fail.js+3 added-3 removed
1 unmodified line
2import process from 'node:process';3import {execa} from '../../index.js';45const [options, file, ...args] = process.argv.slice(2);6const childProcess = execa(file, args, JSON.parse(options));7childProcess.kill(new Error(args[0]));8await childProcess;6const subprocess = execa(file, args, JSON.parse(options));7subprocess.kill(new Error(args[0]));8await subprocess;
modified:test/fixtures/nested-multiple-stdin.js+3 added-3 removed
1 unmodified line
2import 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;6const subprocess = execa('stdin.js', {stdin: JSON.parse(options)});7subprocess.stdin.write('foobar');8const {stdout} = await subprocess;9console.log(stdout);
deleted:test/fixtures/nested-pipe-child-process.js-15 removed
1#!/usr/bin/env node2import process from 'node:process';3import {execa} from '../../index.js';45const [options, file, arg, unpipe] = process.argv.slice(2);6const source = execa(file, [arg], JSON.parse(options));7const destination = execa('stdin.js');8const controller = new AbortController();9const pipePromise = source.pipe(destination, {unpipeSignal: controller.signal});10if (unpipe === 'true') {11 controller.abort();12 destination.stdin.end();13}1415await Promise.allSettled([source, destination, pipePromise]);
deleted:test/fixtures/nested-pipe-process.js-7 removed
1#!/usr/bin/env node2import process from 'node:process';3import {execa} from '../../index.js';45const [sourceOptions, sourceFile, sourceArg, destinationOptions, destinationFile, destinationArg] = process.argv.slice(2);6await execa(sourceFile, [sourceArg], JSON.parse(sourceOptions))7 .pipe(execa(destinationFile, destinationArg === undefined ? [] : [destinationArg], JSON.parse(destinationOptions)));
modified:test/fixtures/nested-pipe-stream.js+4 added-4 removed
1 unmodified line
2import process from 'node:process';3import {execa} from '../../index.js';45const [options, file, arg, unpipe] = process.argv.slice(2);6const childProcess = execa(file, [arg], JSON.parse(options));7childProcess.stdout.pipe(process.stdout);6const subprocess = execa(file, [arg], JSON.parse(options));7subprocess.stdout.pipe(process.stdout);8if (unpipe === 'true') {9 childProcess.stdout.unpipe(process.stdout);9 subprocess.stdout.unpipe(process.stdout);10}1112await childProcess;12await subprocess;
added:test/fixtures/nested-pipe-subprocess.js+15 added
1#!/usr/bin/env node2import process from 'node:process';3import {execa} from '../../index.js';45const [options, file, arg, unpipe] = process.argv.slice(2);6const source = execa(file, [arg], JSON.parse(options));7const destination = execa('stdin.js');8const controller = new AbortController();9const pipePromise = source.pipe(destination, {unpipeSignal: controller.signal});10if (unpipe === 'true') {11 controller.abort();12 destination.stdin.end();13}1415await Promise.allSettled([source, destination, pipePromise]);
added:test/fixtures/nested-pipe-subprocesses.js+7 added
1#!/usr/bin/env node2import process from 'node:process';3import {execa} from '../../index.js';45const [sourceOptions, sourceFile, sourceArg, destinationOptions, destinationFile, destinationArg] = process.argv.slice(2);6await execa(sourceFile, [sourceArg], JSON.parse(sourceOptions))7 .pipe(execa(destinationFile, destinationArg === undefined ? [] : [destinationArg], JSON.parse(destinationOptions)));
modified:test/fixtures/nested-stdio.js+5 added-5 removed
8 unmodified lines
9 ? [process[optionValue[0]], ...optionValue.slice(1)]10 : optionValue;11const stdio = ['ignore', 'inherit', 'inherit'];12stdio[fdNumber] = optionValue;13const childProcess = execa(file, [`${fdNumber}`, ...args], {stdio});13const subprocess = execa(file, [`${fdNumber}`, ...args], {stdio});1415const shouldPipe = Array.isArray(optionValue) && optionValue.includes('pipe');16const hasPipe = childProcess.stdio[fdNumber] !== null;16const hasPipe = subprocess.stdio[fdNumber] !== null;1718if (shouldPipe && !hasPipe) {19 throw new Error(`childProcess.stdio[${fdNumber}] is null.`);19 throw new Error(`subprocess.stdio[${fdNumber}] is null.`);20}2122if (!shouldPipe && hasPipe) {23 throw new Error(`childProcess.stdio[${fdNumber}] should be null.`);23 throw new Error(`subprocess.stdio[${fdNumber}] should be null.`);24}2526await childProcess;26await subprocess;
deleted:test/fixtures/sub-process.js-9 removed
1#!/usr/bin/env node2import process from 'node:process';3import {execa} from '../../index.js';45const cleanup = process.argv[2] === 'true';6const detached = process.argv[3] === 'true';7const subprocess = execa('forever.js', {cleanup, detached});8process.send(subprocess.pid);9await subprocess;
added:test/fixtures/subprocess.js+9 added
1#!/usr/bin/env node2import process from 'node:process';3import {execa} from '../../index.js';45const cleanup = process.argv[2] === 'true';6const detached = process.argv[3] === 'true';7const subprocess = execa('forever.js', {cleanup, detached});8process.send(subprocess.pid);9await subprocess;
modified:test/helpers/early-error.js+2 added-2 removed
1import {execa, execaSync} from '../../index.js';23export const earlyErrorOptions = {killSignal: false};4export const getEarlyErrorProcess = options => execa('empty.js', {...earlyErrorOptions, ...options});5export const getEarlyErrorProcessSync = options => execaSync('empty.js', {...earlyErrorOptions, ...options});4export const getEarlyErrorSubprocess = options => execa('empty.js', {...earlyErrorOptions, ...options});5export const getEarlyErrorSubprocessSync = options => execaSync('empty.js', {...earlyErrorOptions, ...options});67export const expectedEarlyError = {code: 'ERR_INVALID_ARG_TYPE'};
modified:test/helpers/verbose.js+3 added-3 removed
14 unmodified lines
1516export const nestedExecaAsync = nestedExeca.bind(undefined, 'nested.js');17export const nestedExecaSync = nestedExeca.bind(undefined, 'nested-sync.js');1819export const runErrorProcess = async (t, verbose, execaMethod) => {19export const runErrorSubprocess = async (t, verbose, execaMethod) => {20 const {stderr} = await t.throwsAsync(execaMethod('noop-fail.js', ['1', foobarString], {verbose}));21 t.true(stderr.includes('exit code 2'));22 return stderr;23};2425export const runWarningProcess = async (t, execaMethod) => {25export const runWarningSubprocess = async (t, execaMethod) => {26 const {stderr} = await execaMethod('noop-fail.js', ['1', foobarString], {verbose: 'short', reject: false});27 t.true(stderr.includes('exit code 2'));28 return stderr;29};3031export const runEarlyErrorProcess = async (t, execaMethod) => {31export const runEarlyErrorSubprocess = async (t, execaMethod) => {32 const {stderr} = await t.throwsAsync(execaMethod('noop.js', [foobarString], {verbose: 'short', cwd: true}));33 t.true(stderr.includes('The "cwd" option must'));34 return stderr;35};
22 unmodified lines
modified:test/pipe/abort.js+5 added-5 removed
30 unmodified lines
31 t.true(error.shortMessage.includes(error.originalMessage));32 t.true(error.message.includes(error.shortMessage));33};3435test('Can unpipe a single process', async t => {35test('Can unpipe a single subprocess', async t => {36 const abortController = new AbortController();37 const source = execa('stdin.js');38 const destination = execa('stdin.js');39 const pipePromise = source.pipe(destination, {unpipeSignal: abortController.signal});
17 unmodified lines
5758 await assertUnPipeError(t, pipePromise);59});6061test('Can unpipe a process among other sources', async t => {61test('Can unpipe a subprocess among other sources', async t => {62 const abortController = new AbortController();63 const source = execa('stdin.js');64 const secondSource = execa('noop.js', [foobarString]);65 const destination = execa('stdin.js');
10 unmodified lines
76 t.like(await source, {stdout: '.'});77 t.like(await secondSource, {stdout: foobarString});78});7980test('Can unpipe a process among other sources on the same process', async t => {80test('Can unpipe a subprocess among other sources on the same subprocess', async t => {81 const abortController = new AbortController();82 const source = execa('stdin-both.js');83 const destination = execa('stdin.js');84 const pipePromise = source.pipe(destination, {unpipeSignal: abortController.signal});
8 unmodified lines
93 t.like(await destination, {stdout: foobarString});94 t.like(await source, {stdout: foobarString, stderr: foobarString});95});9697test('Can unpipe a process among other destinations', async t => {97test('Can unpipe a subprocess among other destinations', async t => {98 const abortController = new AbortController();99 const source = execa('stdin.js');100 const destination = execa('stdin.js');101 const secondDestination = execa('stdin.js');
11 unmodified lines
113 t.like(await source, {stdout: foobarString});114 t.like(await secondDestination, {stdout: foobarString});115});116117test('Can unpipe then re-pipe a process', async t => {117test('Can unpipe then re-pipe a subprocess', async t => {118 const abortController = new AbortController();119 const source = execa('stdin.js');120 const destination = execa('stdin.js');121 const pipePromise = source.pipe(destination, {unpipeSignal: abortController.signal});
46 unmodified lines
modified:test/pipe/setup.js+11 added-11 removed
3 unmodified lines
4import {fullStdio} from '../helpers/stdio.js';56setFixtureDir();78const pipeToProcess = async (t, fdNumber, from, options) => {8const pipeToSubprocess = async (t, fdNumber, from, options) => {9 const {stdout} = await execa('noop-fd.js', [`${fdNumber}`, 'test'], options)10 .pipe(execa('stdin.js'), {from});11 t.is(stdout, 'test');12};1314test('pipe(...) can pipe', pipeToProcess, 1, undefined, {});15test('pipe(..., {from: "stdout"}) can pipe', pipeToProcess, 1, 'stdout', {});16test('pipe(..., {from: 1}) can pipe', pipeToProcess, 1, 1, {});17test('pipe(..., {from: "stderr"}) stderr can pipe', pipeToProcess, 2, 'stderr', {});18test('pipe(..., {from: 2}) can pipe', pipeToProcess, 2, 2, {});19test('pipe(..., {from: 3}) can pipe', pipeToProcess, 3, 3, fullStdio);20test('pipe(..., {from: "all"}) can pipe stdout', pipeToProcess, 1, 'all', {all: true});21test('pipe(..., {from: "all"}) can pipe stderr', pipeToProcess, 2, 'all', {all: true});22test('pipe(..., {from: "all"}) can pipe stdout even with "stderr: ignore"', pipeToProcess, 1, 'all', {all: true, stderr: 'ignore'});23test('pipe(..., {from: "all"}) can pipe stderr even with "stdout: ignore"', pipeToProcess, 2, 'all', {all: true, stdout: 'ignore'});14test('pipe(...) can pipe', pipeToSubprocess, 1, undefined, {});15test('pipe(..., {from: "stdout"}) can pipe', pipeToSubprocess, 1, 'stdout', {});16test('pipe(..., {from: 1}) can pipe', pipeToSubprocess, 1, 1, {});17test('pipe(..., {from: "stderr"}) stderr can pipe', pipeToSubprocess, 2, 'stderr', {});18test('pipe(..., {from: 2}) can pipe', pipeToSubprocess, 2, 2, {});19test('pipe(..., {from: 3}) can pipe', pipeToSubprocess, 3, 3, fullStdio);20test('pipe(..., {from: "all"}) can pipe stdout', pipeToSubprocess, 1, 'all', {all: true});21test('pipe(..., {from: "all"}) can pipe stderr', pipeToSubprocess, 2, 'all', {all: true});22test('pipe(..., {from: "all"}) can pipe stdout even with "stderr: ignore"', pipeToSubprocess, 1, 'all', {all: true, stderr: 'ignore'});23test('pipe(..., {from: "all"}) can pipe stderr even with "stdout: ignore"', pipeToSubprocess, 2, 'all', {all: true, stdout: 'ignore'});
modified:test/pipe/streaming.js+6 added-6 removed
38 unmodified lines
39 t.is(await secondPipePromise, await destination);40 t.is(await thirdPromise, await destination);41});4243const processesCount = 100;43const subprocessesCount = 100;4445test.serial('Can pipe many sources to same destination', async t => {46 const checkMaxListeners = assertMaxListeners(t);4748 const expectedResults = Array.from({length: processesCount}, (_, index) => `${index}`).sort();48 const expectedResults = Array.from({length: subprocessesCount}, (_, index) => `${index}`).sort();49 const sources = expectedResults.map(expectedResult => execa('noop.js', [expectedResult]));50 const destination = execa('stdin.js');51 const pipePromises = sources.map(source => source.pipe(destination));52
9 unmodified lines
62test.serial('Can pipe same source to many destinations', async t => {63 const checkMaxListeners = assertMaxListeners(t);6465 const source = execa('noop-fd.js', ['1', foobarString]);66 const expectedResults = Array.from({length: processesCount}, (_, index) => `${index}`);66 const expectedResults = Array.from({length: subprocessesCount}, (_, index) => `${index}`);67 const destinations = expectedResults.map(expectedResult => execa('noop-stdin-double.js', [expectedResult]));68 const pipePromises = destinations.map(destination => source.pipe(destination));6970 t.like(await source, {stdout: foobarString});
3 unmodified lines
7475 checkMaxListeners();76});7778test('Can pipe two streams from same process to same destination', async t => {78test('Can pipe two streams from same subprocess to same destination', async t => {79 const source = execa('noop-both.js', [foobarString]);80 const destination = execa('stdin.js');81 const pipePromise = source.pipe(destination);82 const secondPipePromise = source.pipe(destination, {from: 'stderr'});
78 unmodified lines
161 t.is(await secondPipePromise, await destination);162 t.is(await thirdPipePromise, await destination);163});164165test('Can pipe two processes already ended', async t => {165test('Can pipe two subprocesses already ended', async t => {166 const source = execa('noop.js', [foobarString]);167 const destination = execa('stdin.js');168 destination.stdin.end('.');169 await Promise.all([source, destination]);
206 unmodified lines
376 t.deepEqual(sourceResult.pipedFrom, []);377 t.deepEqual(secondSourceResult.pipedFrom, []);378});379380test('Returns pipedFrom from already ended processes', async t => {380test('Returns pipedFrom from already ended subprocesses', async t => {381 const source = execa('noop.js', [foobarString]);382 const destination = execa('stdin.js');383 destination.stdin.end('.');384 await Promise.all([source, destination]);
44 unmodified lines
modified:test/pipe/template.js+16 added-16 removed
5 unmodified lines
6import {foobarString} from '../helpers/input.js';78setFixtureDir();910test('$.pipe(childProcess)', async t => {10test('$.pipe(subprocess)', async t => {11 const {stdout} = await $`noop.js ${foobarString}`.pipe($({stdin: 'pipe'})`stdin.js`);12 t.is(stdout, foobarString);13});1415test('execa.$.pipe(childProcess)', async t => {15test('execa.$.pipe(subprocess)', async t => {16 const {stdout} = await execa('noop.js', [foobarString]).pipe($({stdin: 'pipe'})`stdin.js`);17 t.is(stdout, foobarString);18});1920test('$.pipe.pipe(childProcess)', async t => {20test('$.pipe.pipe(subprocess)', async t => {21 const {stdout} = await $`noop.js ${foobarString}`22 .pipe($({stdin: 'pipe'})`stdin.js`)23 .pipe($({stdin: 'pipe'})`stdin.js`);24 t.is(stdout, foobarString);
54 unmodified lines
79 .pipe('node', ['stdin.js'], {cwd: FIXTURES_DIR});80 t.is(stdout, foobarString);81});8283test('$.pipe(childProcess, pipeOptions)', async t => {83test('$.pipe(subprocess, pipeOptions)', async t => {84 const {stdout} = await $`noop-fd.js 2 ${foobarString}`.pipe($({stdin: 'pipe'})`stdin.js`, {from: 'stderr'});85 t.is(stdout, foobarString);86});8788test('execa.$.pipe(childProcess, pipeOptions)', async t => {88test('execa.$.pipe(subprocess, pipeOptions)', async t => {89 const {stdout} = await execa('noop-fd.js', ['2', foobarString]).pipe($({stdin: 'pipe'})`stdin.js`, {from: 'stderr'});90 t.is(stdout, foobarString);91});9293test('$.pipe.pipe(childProcess, pipeOptions)', async t => {93test('$.pipe.pipe(subprocess, pipeOptions)', async t => {94 const {stdout} = await $`noop-fd.js 2 ${foobarString}`95 .pipe($({stdin: 'pipe'})`noop-stdin-fd.js 2`, {from: 'stderr'})96 .pipe($({stdin: 'pipe'})`stdin.js`, {from: 'stderr'});97 t.is(stdout, foobarString);
66 unmodified lines
164 .pipe('stdin.js', {stripFinalNewline: false});165 t.is(stdout, `${foobarString}\n`);166});167168test('$.pipe(pipeAndProcessOptions)`command`', async t => {168test('$.pipe(pipeAndSubprocessOptions)`command`', async t => {169 const {stdout} = await $`noop-fd.js 2 ${foobarString}\n`.pipe({from: 'stderr', stripFinalNewline: false})`stdin.js`;170 t.is(stdout, `${foobarString}\n`);171});172173test('execa.$.pipe(pipeAndProcessOptions)`command`', async t => {173test('execa.$.pipe(pipeAndSubprocessOptions)`command`', async t => {174 const {stdout} = await execa('noop-fd.js', ['2', `${foobarString}\n`]).pipe({from: 'stderr', stripFinalNewline: false})`stdin.js`;175 t.is(stdout, `${foobarString}\n`);176});177178test('$.pipe.pipe(pipeAndProcessOptions)`command`', async t => {178test('$.pipe.pipe(pipeAndSubprocessOptions)`command`', async t => {179 const {stdout} = await $`noop-fd.js 2 ${foobarString}\n`180 .pipe({from: 'stderr'})`noop-stdin-fd.js 2`181 .pipe({from: 'stderr', stripFinalNewline: false})`stdin.js`;182 t.is(stdout, `${foobarString}\n`);183});184185test('$.pipe("file", pipeAndProcessOptions)', async t => {185test('$.pipe("file", pipeAndSubprocessOptions)', async t => {186 const {stdout} = await $`noop-fd.js 2 ${foobarString}\n`.pipe('stdin.js', {from: 'stderr', stripFinalNewline: false});187 t.is(stdout, `${foobarString}\n`);188});189190test('execa.$.pipe("file", pipeAndProcessOptions)', async t => {190test('execa.$.pipe("file", pipeAndSubprocessOptions)', async t => {191 const {stdout} = await execa('noop-fd.js', ['2', `${foobarString}\n`]).pipe('stdin.js', {from: 'stderr', stripFinalNewline: false});192 t.is(stdout, `${foobarString}\n`);193});194195test('$.pipe.pipe("file", pipeAndProcessOptions)', async t => {195test('$.pipe.pipe("file", pipeAndSubprocessOptions)', async t => {196 const {stdout} = await $`noop-fd.js 2 ${foobarString}\n`197 .pipe({from: 'stderr'})`noop-stdin-fd.js 2`198 .pipe('stdin.js', {from: 'stderr', stripFinalNewline: false});199 t.is(stdout, `${foobarString}\n`);
25 unmodified lines
225 const {stdout} = await execa('noop.js', [foobarString]).pipe('stdin.js', {stdin: 'ignore'});226 t.is(stdout, foobarString);227});228229test('execa.pipe(childProcess) does not force "stdin: pipe"', async t => {229test('execa.pipe(subprocess) does not force "stdin: pipe"', async t => {230 await t.throwsAsync(231 execa('noop.js', [foobarString]).pipe(execa('stdin.js', {stdin: 'ignore'})),232 {message: /stdin must be available/},233 );234});235236test('$.pipe(options)(childProcess) fails', async t => {236test('$.pipe(options)(subprocess) fails', async t => {237 await t.throwsAsync(238 $`empty.js`.pipe({stdout: 'pipe'})($`empty.js`),239 {message: /Please use \.pipe/},240 );241});242243test('execa.$.pipe(options)(childProcess) fails', async t => {243test('execa.$.pipe(options)(subprocess) fails', async t => {244 await t.throwsAsync(245 execa('empty.js').pipe({stdout: 'pipe'})($`empty.js`),246 {message: /Please use \.pipe/},247 );
19 unmodified lines
267 {message: /must be a template string/},268 );269};270271test('$.pipe(nonExecaChildProcess) fails', testInvalidPipe, spawn('node', ['--version']));271test('$.pipe(nonExecaSubprocess) fails', testInvalidPipe, spawn('node', ['--version']));272test('$.pipe(false) fails', testInvalidPipe, false);
modified:test/pipe/validate.js+7 added-7 removed
3 unmodified lines
4import test from 'ava';5import {execa} from '../../index.js';6import {setFixtureDir} from '../helpers/fixtures-dir.js';7import {foobarString} from '../helpers/input.js';8import {getEarlyErrorProcess} from '../helpers/early-error.js';8import {getEarlyErrorSubprocess} from '../helpers/early-error.js';910setFixtureDir();1112const assertPipeError = async (t, pipePromise, message) => {
36 unmodified lines
49 await assertPipeError(50 t,51 execa('empty.js')52 .pipe(getDestination()),53 'an Execa child process',53 'an Execa subprocess',54 );55};5657test('pipe() cannot pipe to non-processes', invalidDestination, () => new PassThrough());58test('pipe() cannot pipe to non-Execa processes', invalidDestination, () => spawn('node', ['--version']));57test('pipe() cannot pipe to non-subprocesses', invalidDestination, () => new PassThrough());58test('pipe() cannot pipe to non-Execa subprocesses', invalidDestination, () => spawn('node', ['--version']));5960test('pipe() "from" option cannot be "stdin"', async t => {61 await assertPipeError(62 t,
103 unmodified lines
166test('Source stream is aborted when second argument is invalid', async t => {167 const source = execa('noop.js', [foobarString]);168 const pipePromise = source.pipe(false);169170 await assertPipeError(t, pipePromise, 'an Execa child process');170 await assertPipeError(t, pipePromise, 'an Execa subprocess');171 t.like(await source, {stdout: ''});172});173174test('Both arguments might be invalid', async t => {175 const source = execa('empty.js', {stdout: 'ignore'});176 const pipePromise = source.pipe(false);177178 await assertPipeError(t, pipePromise, 'an Execa child process');178 await assertPipeError(t, pipePromise, 'an Execa subprocess');179 t.like(await source, {stdout: undefined});180});181182test('Sets the right error message when the "all" option is incompatible - execa.$', async t => {
18 unmodified lines
201202test('Sets the right error message when the "all" option is incompatible - early error', async t => {203 await assertPipeError(204 t,205 getEarlyErrorProcess()205 getEarlyErrorSubprocess()206 .pipe(execa('stdin.js', {all: false}))207 .pipe(execa('empty.js'), {from: 'all'}),208 '"all" option must be true',209 );
1 unmodified line
modified:test/return/clone.js+21 added-21 removed
4 unmodified lines
56setFixtureDir();78const testUnusualError = async (t, error, expectedOriginalMessage = String(error)) => {9 const childProcess = execa('empty.js');10 childProcess.emit('error', error);11 const {originalMessage, shortMessage, message} = await t.throwsAsync(childProcess);9 const subprocess = execa('empty.js');10 subprocess.emit('error', error);11 const {originalMessage, shortMessage, message} = await t.throwsAsync(subprocess);12 t.is(originalMessage, expectedOriginalMessage);13 t.true(shortMessage.includes(expectedOriginalMessage));14 t.is(message, shortMessage);15};
10 unmodified lines
26test('error instance can be an error with an empty message', testUnusualError, new Error(''), '');27test('error instance can be undefined', testUnusualError, undefined, '');2829test('error instance can be a plain object', async t => {30 const childProcess = execa('empty.js');31 childProcess.emit('error', {message: foobarString});32 await t.throwsAsync(childProcess, {message: new RegExp(foobarString)});30 const subprocess = execa('empty.js');31 subprocess.emit('error', {message: foobarString});32 await t.throwsAsync(subprocess, {message: new RegExp(foobarString)});33});3435const runAndFail = (t, fixtureName, argument, error) => {36 const childProcess = execa(fixtureName, [argument]);37 childProcess.emit('error', error);38 return t.throwsAsync(childProcess);36 const subprocess = execa(fixtureName, [argument]);37 subprocess.emit('error', error);38 return t.throwsAsync(subprocess);39};4041const runAndClone = async (t, initialError) => {42 const previousError = await runAndFail(t, 'empty.js', 'foo', initialError);
72 unmodified lines
115 error.message = newMessage;116 t.false(error.stack.includes(newMessage));117 error.message = message;118119 const childProcess = execa('empty.js');120 childProcess.emit('error', error);121 t.is(await t.throwsAsync(childProcess), error);119 const subprocess = execa('empty.js');120 subprocess.emit('error', error);121 t.is(await t.throwsAsync(subprocess), error);122 t.is(error.message, `Command failed: empty.js\n${message}`);123 t.true(error.stack.startsWith(`Error: ${error.message}`));124});125126test('error.stack is set even if memoized with an unusual error.name', async t => {127 const childProcess = execa('empty.js');128 childProcess.stdin.destroy();129 const error = await t.throwsAsync(childProcess);127 const subprocess = execa('empty.js');128 subprocess.stdin.destroy();129 const error = await t.throwsAsync(subprocess);130 t.is(error.message, 'Command failed with ERR_STREAM_PREMATURE_CLOSE: empty.js\nPremature close');131 t.true(error.stack.startsWith(`Error [ERR_STREAM_PREMATURE_CLOSE]: ${error.message}`));132});133
1 unmodified line
135 const message = 'test';136 const error = new Error(message);137 const stack = error.stack.split('\n').filter(line => line.trim().startsWith('at ')).join('\n');138139 const childProcess = execa('empty.js');140 childProcess.emit('error', error);141 t.is(await t.throwsAsync(childProcess), error);139 const subprocess = execa('empty.js');140 subprocess.emit('error', error);141 t.is(await t.throwsAsync(subprocess), error);142143 const secondChildProcess = execa('empty.js');144 secondChildProcess.emit('error', error);145 const secondError = await t.throwsAsync(secondChildProcess);143 const secondSubprocess = execa('empty.js');144 secondSubprocess.emit('error', error);145 const secondError = await t.throwsAsync(secondSubprocess);146 t.not(secondError, error);147 t.is(secondError.message, `Command failed: empty.js\n${message}`);148 t.is(secondError.stack, `Error: Command failed: empty.js\n${message}\n${stack}`);149});
1 unmodified line
modified:test/return/duration.js+3 added-3 removed
1import test from 'ava';2import {execa, execaSync} from '../../index.js';3import {setFixtureDir} from '../helpers/fixtures-dir.js';4import {getEarlyErrorProcess, getEarlyErrorProcessSync} from '../helpers/early-error.js';4import {getEarlyErrorSubprocess, getEarlyErrorSubprocessSync} from '../helpers/early-error.js';56setFixtureDir();78const assertDurationMs = (t, durationMs) => {
26 unmodified lines
35 assertDurationMs(t, durationMs);36});3738test('error.durationMs - early validation', async t => {39 const {durationMs} = await t.throwsAsync(getEarlyErrorProcess());39 const {durationMs} = await t.throwsAsync(getEarlyErrorSubprocess());40 assertDurationMs(t, durationMs);41});4243test('error.durationMs - early validation, sync', t => {44 const {durationMs} = t.throws(getEarlyErrorProcessSync);44 const {durationMs} = t.throws(getEarlyErrorSubprocessSync);45 assertDurationMs(t, durationMs);46});4748test('error.durationMs - unpipeSignal', async t => {
14 unmodified lines
modified:test/return/early-error.js+17 added-17 removed
1import process from 'node:process';2import test from 'ava';3import {execa, execaSync, $} from '../../index.js';4import {setFixtureDir} from '../helpers/fixtures-dir.js';5import {earlyErrorOptions, getEarlyErrorProcess, getEarlyErrorProcessSync, expectedEarlyError} from '../helpers/early-error.js';5import {earlyErrorOptions, getEarlyErrorSubprocess, getEarlyErrorSubprocessSync, expectedEarlyError} from '../helpers/early-error.js';67setFixtureDir();89const isWindows = process.platform === 'win32';
5 unmodified lines
15 }, {message: ENOENT_REGEXP});16});1718const testEarlyErrorShape = async (t, reject) => {19 const subprocess = getEarlyErrorProcess({reject});19 const subprocess = getEarlyErrorSubprocess({reject});20 t.notThrows(() => {21 subprocess.catch(() => {});22 subprocess.unref();23 subprocess.on('error', () => {});
3 unmodified lines
27test('child_process.spawn() early errors have correct shape', testEarlyErrorShape, true);28test('child_process.spawn() early errors have correct shape - reject false', testEarlyErrorShape, false);2930test('child_process.spawn() early errors are propagated', async t => {31 await t.throwsAsync(getEarlyErrorProcess(), expectedEarlyError);31 await t.throwsAsync(getEarlyErrorSubprocess(), expectedEarlyError);32});3334test('child_process.spawn() early errors are returned', async t => {35 const {failed} = await getEarlyErrorProcess({reject: false});35 const {failed} = await getEarlyErrorSubprocess({reject: false});36 t.true(failed);37});3839test('child_process.spawnSync() early errors are propagated with a correct shape', t => {40 t.throws(getEarlyErrorProcessSync, expectedEarlyError);40 t.throws(getEarlyErrorSubprocessSync, expectedEarlyError);41});4243test('child_process.spawnSync() early errors are propagated with a correct shape - reject false', t => {44 const {failed} = getEarlyErrorProcessSync({reject: false});44 const {failed} = getEarlyErrorSubprocessSync({reject: false});45 t.true(failed);46});4748if (!isWindows) {
4 unmodified lines
53 test('execa() rejects with correct error and doesn\'t throw if running non-executable with input', async t => {54 await t.throwsAsync(execa('non-executable.js', {input: 'Hey!'}), {message: /EACCES/});55 });5657 test('write to fast-exit process', async t => {57 test('write to fast-exit subprocess', async t => {58 // Try-catch here is necessary, because this test is not 100% accurate59 // Sometimes process can manage to accept input before exiting59 // Sometimes subprocess can manage to accept input before exiting60 try {61 await execa(`fast-exit-${process.platform}`, [], {input: 'data'});62 t.pass();63 } catch (error) {
1 unmodified line
65 }66 });67}6869const testEarlyErrorPipe = async (t, getChildProcess) => {70 await t.throwsAsync(getChildProcess(), expectedEarlyError);69const testEarlyErrorPipe = async (t, getSubprocess) => {70 await t.throwsAsync(getSubprocess(), expectedEarlyError);71};7273test('child_process.spawn() early errors on source can use .pipe()', testEarlyErrorPipe, () => getEarlyErrorProcess().pipe(execa('empty.js')));74test('child_process.spawn() early errors on destination can use .pipe()', testEarlyErrorPipe, () => execa('empty.js').pipe(getEarlyErrorProcess()));75test('child_process.spawn() early errors on source and destination can use .pipe()', testEarlyErrorPipe, () => getEarlyErrorProcess().pipe(getEarlyErrorProcess()));76test('child_process.spawn() early errors can use .pipe() multiple times', testEarlyErrorPipe, () => getEarlyErrorProcess().pipe(getEarlyErrorProcess()).pipe(getEarlyErrorProcess()));73test('child_process.spawn() early errors on source can use .pipe()', testEarlyErrorPipe, () => getEarlyErrorSubprocess().pipe(execa('empty.js')));74test('child_process.spawn() early errors on destination can use .pipe()', testEarlyErrorPipe, () => execa('empty.js').pipe(getEarlyErrorSubprocess()));75test('child_process.spawn() early errors on source and destination can use .pipe()', testEarlyErrorPipe, () => getEarlyErrorSubprocess().pipe(getEarlyErrorSubprocess()));76test('child_process.spawn() early errors can use .pipe() multiple times', testEarlyErrorPipe, () => getEarlyErrorSubprocess().pipe(getEarlyErrorSubprocess()).pipe(getEarlyErrorSubprocess()));77test('child_process.spawn() early errors can use .pipe``', testEarlyErrorPipe, () => $(earlyErrorOptions)`empty.js`.pipe(earlyErrorOptions)`empty.js`);78test('child_process.spawn() early errors can use .pipe`` multiple times', testEarlyErrorPipe, () => $(earlyErrorOptions)`empty.js`.pipe(earlyErrorOptions)`empty.js`.pipe`empty.js`);7980const testEarlyErrorStream = async (t, getStreamProperty, all) => {81 const childProcess = getEarlyErrorProcess({all});82 getStreamProperty(childProcess).on('end', () => {});83 await t.throwsAsync(childProcess);81 const subprocess = getEarlyErrorSubprocess({all});82 getStreamProperty(subprocess).on('end', () => {});83 await t.throwsAsync(subprocess);84};8586test('child_process.spawn() early errors can use .stdin', testEarlyErrorStream, ({stdin}) => stdin, false);87test('child_process.spawn() early errors can use .stdout', testEarlyErrorStream, ({stdout}) => stdout, false);
3 unmodified lines
modified:test/return/error.js+6 added-6 removed
115 unmodified lines
116 const {failed} = await t.throwsAsync(execa('fail.js'));117 t.true(failed);118});119120test('error.isTerminated is true if process was killed directly', async t => {120test('error.isTerminated is true if subprocess was killed directly', async t => {121 const subprocess = execa('forever.js', {killSignal: 'SIGINT'});122123 subprocess.kill();124
4 unmodified lines
129 t.is(shortMessage, 'Command was killed with SIGINT (User interruption with CTRL-C): forever.js');130 t.is(message, shortMessage);131});132133test('error.isTerminated is true if process was killed indirectly', async t => {133test('error.isTerminated is true if subprocess was killed indirectly', async t => {134 const subprocess = execa('forever.js', {killSignal: 'SIGHUP'});135136 process.kill(subprocess.pid, 'SIGINT');137138 // `process.kill()` is emulated by Node.js on Windows138 // `subprocess.kill()` is emulated by Node.js on Windows139 if (isWindows) {140 const {isTerminated, signal} = await t.throwsAsync(subprocess, {message: /failed with exit code 1/});141 t.is(isTerminated, false);142 t.is(signal, undefined);
8 unmodified lines
151 const {isTerminated} = await execa('noop.js');152 t.false(isTerminated);153});154155test('result.isTerminated is false if not killed and childProcess.kill() was called', async t => {155test('result.isTerminated is false if not killed and subprocess.kill() was called', async t => {156 const subprocess = execa('noop.js');157 subprocess.kill(0);158 t.true(subprocess.killed);159 const {isTerminated} = await subprocess;
4 unmodified lines
164 const {isTerminated} = execaSync('noop.js');165 t.false(isTerminated);166});167168test('result.isTerminated is false on process error', async t => {168test('result.isTerminated is false on subprocess error', async t => {169 const {isTerminated} = await t.throwsAsync(execa('wrong command'));170 t.false(isTerminated);171});172173test('result.isTerminated is false on process error, in sync mode', t => {173test('result.isTerminated is false on subprocess error, in sync mode', t => {174 const {isTerminated} = t.throws(() => {175 execaSync('wrong command');176 });177 t.false(isTerminated);
11 unmodified lines
modified:test/return/output.js+2 added-2 removed
81 unmodified lines
8283// `error.code` is OS-specific here84const SPAWN_ERROR_CODES = new Set(['EINVAL', 'ENOTSUP', 'EPERM']);8586test('stdout/stderr/stdio on process spawning errors', async t => {86test('stdout/stderr/stdio on subprocess spawning errors', async t => {87 const {code, stdout, stderr, stdio} = await t.throwsAsync(execa('empty.js', {uid: -1}));88 t.true(SPAWN_ERROR_CODES.has(code));89 t.is(stdout, undefined);90 t.is(stderr, undefined);91 t.deepEqual(stdio, [undefined, undefined, undefined]);92});9394test('stdout/stderr/all/stdio on process spawning errors - sync', t => {94test('stdout/stderr/all/stdio on subprocess spawning errors - sync', t => {95 const {code, stdout, stderr, stdio} = t.throws(() => {96 execaSync('empty.js', {uid: -1});97 });98 t.true(SPAWN_ERROR_CODES.has(code));
44 unmodified lines
modified:test/stdio/async.js+6 added-6 removed
21 unmodified lines
22const onStdinRemoveListener = () => once(process.stdin, 'removeListener', {cleanup: true});2324const testListenersCleanup = async (t, isMultiple) => {25 const streamsPreviousListeners = getStandardStreamsListeners();26 const childProcess = execa('empty.js', getComplexStdio(isMultiple));26 const subprocess = execa('empty.js', getComplexStdio(isMultiple));27 t.notDeepEqual(getStandardStreamsListeners(), streamsPreviousListeners);28 await childProcess;28 await subprocess;29 await onStdinRemoveListener();30 if (isMultiple) {31 await onStdinRemoveListener();32 }
6 unmodified lines
3940test.serial('process.std* listeners are cleaned up on success with a single input', testListenersCleanup, false);41test.serial('process.std* listeners are cleaned up on success with multiple inputs', testListenersCleanup, true);4243const processesCount = 100;43const subprocessesCount = 100;4445test.serial('Can spawn many processes in parallel', async t => {45test.serial('Can spawn many subprocesses in parallel', async t => {46 const results = await Promise.all(47 Array.from({length: processesCount}, () => execa('noop.js', [foobarString])),47 Array.from({length: subprocessesCount}, () => execa('noop.js', [foobarString])),48 );49 t.true(results.every(({stdout}) => stdout === foobarString));50});51
5 unmodified lines
57 }5859 try {60 const results = await Promise.all(61 Array.from({length: processesCount}, () => execa('empty.js', getComplexStdio(isMultiple))),61 Array.from({length: subprocessesCount}, () => execa('empty.js', getComplexStdio(isMultiple))),62 );63 t.true(results.every(({exitCode}) => exitCode === 0));64 } finally {65 await setImmediate();
20 unmodified lines
modified:test/stdio/encoding-final.js+3 added-3 removed
17 unmodified lines
18 const {stdio} = await execaMethod('noop-fd.js', [`${fdNumber}`, STRING_TO_ENCODE], {...fullStdio, encoding});19 compareValues(t, stdio[fdNumber], encoding);2021 if (execaMethod !== execaSync) {22 const childProcess = execaMethod('noop-fd.js', [`${fdNumber}`, STRING_TO_ENCODE], {...fullStdio, encoding, buffer: false});22 const subprocess = execaMethod('noop-fd.js', [`${fdNumber}`, STRING_TO_ENCODE], {...fullStdio, encoding, buffer: false});23 const getStreamMethod = encoding === 'buffer' ? getStreamAsBuffer : getStream;24 const result = await getStreamMethod(childProcess.stdio[fdNumber]);24 const result = await getStreamMethod(subprocess.stdio[fdNumber]);25 compareValues(t, result, encoding);26 await childProcess;26 await subprocess;27 }2829 if (fdNumber === 3) {30 return;
173 unmodified lines
modified:test/stdio/encoding-transform.js+10 added-10 removed
18 unmodified lines
19});2021// eslint-disable-next-line max-params22const testGeneratorFirstEncoding = async (t, input, encoding, output, objectMode) => {23 const childProcess = execa('stdin.js', {stdin: getTypeofGenerator(objectMode), encoding});24 childProcess.stdin.end(input);25 const {stdout} = await childProcess;23 const subprocess = execa('stdin.js', {stdin: getTypeofGenerator(objectMode), encoding});24 subprocess.stdin.end(input);25 const {stdout} = await subprocess;26 const result = Buffer.from(stdout, encoding).toString();27 t.is(result, output);28};29
10 unmodified lines
40test('First generator argument can be objects with objectMode', testGeneratorFirstEncoding, foobarObject, 'utf8', '[object Object]', true);4142const testEncodingIgnored = async (t, encoding) => {43 const input = Buffer.from(foobarString).toString(encoding);44 const childProcess = execa('stdin.js', {stdin: noopGenerator(true)});45 childProcess.stdin.end(input, encoding);46 const {stdout} = await childProcess;44 const subprocess = execa('stdin.js', {stdin: noopGenerator(true)});45 subprocess.stdin.end(input, encoding);46 const {stdout} = await subprocess;47 t.is(stdout, input);48};4950test('Write call encoding "utf8" is ignored with objectMode', testEncodingIgnored, 'utf8');
116 unmodified lines
167const breakingLength = multibyteUint8Array.length * 0.75;168const brokenSymbol = '\uFFFD';169170const testMultibyte = async (t, objectMode) => {171 const childProcess = execa('stdin.js', {stdin: noopGenerator(objectMode)});172 childProcess.stdin.write(multibyteUint8Array.slice(0, breakingLength));171 const subprocess = execa('stdin.js', {stdin: noopGenerator(objectMode)});172 subprocess.stdin.write(multibyteUint8Array.slice(0, breakingLength));173 await scheduler.yield();174 childProcess.stdin.end(multibyteUint8Array.slice(breakingLength));175 const {stdout} = await childProcess;174 subprocess.stdin.end(multibyteUint8Array.slice(breakingLength));175 const {stdout} = await subprocess;176 t.is(stdout, multibyteString);177};178179test('Generator handles multibyte characters with Uint8Array', testMultibyte, false);
9 unmodified lines
modified:test/stdio/file-descriptor.js+2 added-2 removed
28 unmodified lines
29 const {stdout} = await subprocess;30 t.is(stdout, 'unicorns');31};3233test('you can write to child.stdin', testStdinWrite, 0);34test('you can write to child.stdio[*]', testStdinWrite, 3);33test('you can write to subprocess.stdin', testStdinWrite, 0);34test('you can write to subprocess.stdio[*]', testStdinWrite, 3);
modified:test/stdio/file-path.js+2 added-2 removed
207 unmodified lines
208 await t.throwsAsync(execa('stdin.js', {stdin: mapFilePath(filePath), timeout: 1}), {message: /timed out/});209 await rm(filePath);210};211212test('Passing an input file path when process exits does not make promise hang', testInputFileHanging, getAbsolutePath);213test('Passing an input file URL when process exits does not make promise hang', testInputFileHanging, pathToFileURL);212test('Passing an input file path when subprocess exits does not make promise hang', testInputFileHanging, getAbsolutePath);213test('Passing an input file URL when subprocess exits does not make promise hang', testInputFileHanging, pathToFileURL);
modified:test/stdio/generator.js+51 added-51 removed
61 unmodified lines
6263// eslint-disable-next-line max-params64const testGeneratorInputPipe = async (t, useShortcutProperty, objectMode, addNoopTransform, input) => {65 const {generators, output} = getInputObjectMode(objectMode, addNoopTransform);66 const childProcess = execa('stdin-fd.js', ['0'], getStdio(0, generators));67 const stream = useShortcutProperty ? childProcess.stdin : childProcess.stdio[0];66 const subprocess = execa('stdin-fd.js', ['0'], getStdio(0, generators));67 const stream = useShortcutProperty ? subprocess.stdin : subprocess.stdio[0];68 stream.end(...input);69 const {stdout} = await childProcess;69 const {stdout} = await subprocess;70 t.is(stdout, output);71};7273test('Can use generators with childProcess.stdio[0] and default encoding', testGeneratorInputPipe, false, false, false, [foobarString, 'utf8']);74test('Can use generators with childProcess.stdin and default encoding', testGeneratorInputPipe, true, false, false, [foobarString, 'utf8']);75test('Can use generators with childProcess.stdio[0] and encoding "buffer"', testGeneratorInputPipe, false, false, false, [foobarBuffer, 'buffer']);76test('Can use generators with childProcess.stdin and encoding "buffer"', testGeneratorInputPipe, true, false, false, [foobarBuffer, 'buffer']);77test('Can use generators with childProcess.stdio[0] and encoding "hex"', testGeneratorInputPipe, false, false, false, [foobarHex, 'hex']);78test('Can use generators with childProcess.stdin and encoding "hex"', testGeneratorInputPipe, true, false, false, [foobarHex, 'hex']);79test('Can use generators with childProcess.stdio[0], objectMode', testGeneratorInputPipe, false, true, false, [foobarObject]);80test('Can use generators with childProcess.stdin, objectMode', testGeneratorInputPipe, true, true, false, [foobarObject]);81test('Can use generators with childProcess.stdio[0] and default encoding, noop transform', testGeneratorInputPipe, false, false, true, [foobarString, 'utf8']);82test('Can use generators with childProcess.stdin and default encoding, noop transform', testGeneratorInputPipe, true, false, true, [foobarString, 'utf8']);83test('Can use generators with childProcess.stdio[0] and encoding "buffer", noop transform', testGeneratorInputPipe, false, false, true, [foobarBuffer, 'buffer']);84test('Can use generators with childProcess.stdin and encoding "buffer", noop transform', testGeneratorInputPipe, true, false, true, [foobarBuffer, 'buffer']);85test('Can use generators with childProcess.stdio[0] and encoding "hex", noop transform', testGeneratorInputPipe, false, false, true, [foobarHex, 'hex']);86test('Can use generators with childProcess.stdin and encoding "hex", noop transform', testGeneratorInputPipe, true, false, true, [foobarHex, 'hex']);87test('Can use generators with childProcess.stdio[0], objectMode, noop transform', testGeneratorInputPipe, false, true, true, [foobarObject]);88test('Can use generators with childProcess.stdin, objectMode, noop transform', testGeneratorInputPipe, true, true, true, [foobarObject]);73test('Can use generators with subprocess.stdio[0] and default encoding', testGeneratorInputPipe, false, false, false, [foobarString, 'utf8']);74test('Can use generators with subprocess.stdin and default encoding', testGeneratorInputPipe, true, false, false, [foobarString, 'utf8']);75test('Can use generators with subprocess.stdio[0] and encoding "buffer"', testGeneratorInputPipe, false, false, false, [foobarBuffer, 'buffer']);76test('Can use generators with subprocess.stdin and encoding "buffer"', testGeneratorInputPipe, true, false, false, [foobarBuffer, 'buffer']);77test('Can use generators with subprocess.stdio[0] and encoding "hex"', testGeneratorInputPipe, false, false, false, [foobarHex, 'hex']);78test('Can use generators with subprocess.stdin and encoding "hex"', testGeneratorInputPipe, true, false, false, [foobarHex, 'hex']);79test('Can use generators with subprocess.stdio[0], objectMode', testGeneratorInputPipe, false, true, false, [foobarObject]);80test('Can use generators with subprocess.stdin, objectMode', testGeneratorInputPipe, true, true, false, [foobarObject]);81test('Can use generators with subprocess.stdio[0] and default encoding, noop transform', testGeneratorInputPipe, false, false, true, [foobarString, 'utf8']);82test('Can use generators with subprocess.stdin and default encoding, noop transform', testGeneratorInputPipe, true, false, true, [foobarString, 'utf8']);83test('Can use generators with subprocess.stdio[0] and encoding "buffer", noop transform', testGeneratorInputPipe, false, false, true, [foobarBuffer, 'buffer']);84test('Can use generators with subprocess.stdin and encoding "buffer", noop transform', testGeneratorInputPipe, true, false, true, [foobarBuffer, 'buffer']);85test('Can use generators with subprocess.stdio[0] and encoding "hex", noop transform', testGeneratorInputPipe, false, false, true, [foobarHex, 'hex']);86test('Can use generators with subprocess.stdin and encoding "hex", noop transform', testGeneratorInputPipe, true, false, true, [foobarHex, 'hex']);87test('Can use generators with subprocess.stdio[0], objectMode, noop transform', testGeneratorInputPipe, false, true, true, [foobarObject]);88test('Can use generators with subprocess.stdin, objectMode, noop transform', testGeneratorInputPipe, true, true, true, [foobarObject]);8990const testGeneratorStdioInputPipe = async (t, objectMode, addNoopTransform) => {91 const {input, generators, output} = getInputObjectMode(objectMode, addNoopTransform);92 const childProcess = execa('stdin-fd.js', ['3'], getStdio(3, [new Uint8Array(), ...generators]));93 childProcess.stdio[3].write(Array.isArray(input) ? input[0] : input);94 const {stdout} = await childProcess;92 const subprocess = execa('stdin-fd.js', ['3'], getStdio(3, [new Uint8Array(), ...generators]));93 subprocess.stdio[3].write(Array.isArray(input) ? input[0] : input);94 const {stdout} = await subprocess;95 t.is(stdout, output);96};9798test('Can use generators with childProcess.stdio[*] as input', testGeneratorStdioInputPipe, false, false);99test('Can use generators with childProcess.stdio[*] as input, objectMode', testGeneratorStdioInputPipe, true, false);100test('Can use generators with childProcess.stdio[*] as input, noop transform', testGeneratorStdioInputPipe, false, true);101test('Can use generators with childProcess.stdio[*] as input, objectMode, noop transform', testGeneratorStdioInputPipe, true, true);98test('Can use generators with subprocess.stdio[*] as input', testGeneratorStdioInputPipe, false, false);99test('Can use generators with subprocess.stdio[*] as input, objectMode', testGeneratorStdioInputPipe, true, false);100test('Can use generators with subprocess.stdio[*] as input, noop transform', testGeneratorStdioInputPipe, false, true);101test('Can use generators with subprocess.stdio[*] as input, objectMode, noop transform', testGeneratorStdioInputPipe, true, true);102103// eslint-disable-next-line max-params104const testGeneratorOutput = async (t, fdNumber, reject, useShortcutProperty, objectMode, addNoopTransform) => {105 const {generators, output} = getOutputObjectMode(objectMode, addNoopTransform);
46 unmodified lines
152153// eslint-disable-next-line max-params154const testGeneratorOutputPipe = async (t, fdNumber, useShortcutProperty, objectMode, addNoopTransform) => {155 const {generators, output, getStreamMethod} = getOutputObjectMode(objectMode, addNoopTransform);156 const childProcess = execa('noop-fd.js', [`${fdNumber}`, foobarString], {...getStdio(fdNumber, generators), buffer: false});157 const stream = useShortcutProperty ? [childProcess.stdout, childProcess.stderr][fdNumber - 1] : childProcess.stdio[fdNumber];158 const [result] = await Promise.all([getStreamMethod(stream), childProcess]);156 const subprocess = execa('noop-fd.js', [`${fdNumber}`, foobarString], {...getStdio(fdNumber, generators), buffer: false});157 const stream = useShortcutProperty ? [subprocess.stdout, subprocess.stderr][fdNumber - 1] : subprocess.stdio[fdNumber];158 const [result] = await Promise.all([getStreamMethod(stream), subprocess]);159 t.deepEqual(result, output);160};161162test('Can use generators with childProcess.stdio[1]', testGeneratorOutputPipe, 1, false, false, false);163test('Can use generators with childProcess.stdout', testGeneratorOutputPipe, 1, true, false, false);164test('Can use generators with childProcess.stdio[2]', testGeneratorOutputPipe, 2, false, false, false);165test('Can use generators with childProcess.stderr', testGeneratorOutputPipe, 2, true, false, false);166test('Can use generators with childProcess.stdio[*] as output', testGeneratorOutputPipe, 3, false, false, false);167test('Can use generators with childProcess.stdio[1], objectMode', testGeneratorOutputPipe, 1, false, true, false);168test('Can use generators with childProcess.stdout, objectMode', testGeneratorOutputPipe, 1, true, true, false);169test('Can use generators with childProcess.stdio[2], objectMode', testGeneratorOutputPipe, 2, false, true, false);170test('Can use generators with childProcess.stderr, objectMode', testGeneratorOutputPipe, 2, true, true, false);171test('Can use generators with childProcess.stdio[*] as output, objectMode', testGeneratorOutputPipe, 3, false, true, false);172test('Can use generators with childProcess.stdio[1], noop transform', testGeneratorOutputPipe, 1, false, false, true);173test('Can use generators with childProcess.stdout, noop transform', testGeneratorOutputPipe, 1, true, false, true);174test('Can use generators with childProcess.stdio[2], noop transform', testGeneratorOutputPipe, 2, false, false, true);175test('Can use generators with childProcess.stderr, noop transform', testGeneratorOutputPipe, 2, true, false, true);176test('Can use generators with childProcess.stdio[*] as output, noop transform', testGeneratorOutputPipe, 3, false, false, true);177test('Can use generators with childProcess.stdio[1], objectMode, noop transform', testGeneratorOutputPipe, 1, false, true, true);178test('Can use generators with childProcess.stdout, objectMode, noop transform', testGeneratorOutputPipe, 1, true, true, true);179test('Can use generators with childProcess.stdio[2], objectMode, noop transform', testGeneratorOutputPipe, 2, false, true, true);180test('Can use generators with childProcess.stderr, objectMode, noop transform', testGeneratorOutputPipe, 2, true, true, true);181test('Can use generators with childProcess.stdio[*] as output, objectMode, noop transform', testGeneratorOutputPipe, 3, false, true, true);162test('Can use generators with subprocess.stdio[1]', testGeneratorOutputPipe, 1, false, false, false);163test('Can use generators with subprocess.stdout', testGeneratorOutputPipe, 1, true, false, false);164test('Can use generators with subprocess.stdio[2]', testGeneratorOutputPipe, 2, false, false, false);165test('Can use generators with subprocess.stderr', testGeneratorOutputPipe, 2, true, false, false);166test('Can use generators with subprocess.stdio[*] as output', testGeneratorOutputPipe, 3, false, false, false);167test('Can use generators with subprocess.stdio[1], objectMode', testGeneratorOutputPipe, 1, false, true, false);168test('Can use generators with subprocess.stdout, objectMode', testGeneratorOutputPipe, 1, true, true, false);169test('Can use generators with subprocess.stdio[2], objectMode', testGeneratorOutputPipe, 2, false, true, false);170test('Can use generators with subprocess.stderr, objectMode', testGeneratorOutputPipe, 2, true, true, false);171test('Can use generators with subprocess.stdio[*] as output, objectMode', testGeneratorOutputPipe, 3, false, true, false);172test('Can use generators with subprocess.stdio[1], noop transform', testGeneratorOutputPipe, 1, false, false, true);173test('Can use generators with subprocess.stdout, noop transform', testGeneratorOutputPipe, 1, true, false, true);174test('Can use generators with subprocess.stdio[2], noop transform', testGeneratorOutputPipe, 2, false, false, true);175test('Can use generators with subprocess.stderr, noop transform', testGeneratorOutputPipe, 2, true, false, true);176test('Can use generators with subprocess.stdio[*] as output, noop transform', testGeneratorOutputPipe, 3, false, false, true);177test('Can use generators with subprocess.stdio[1], objectMode, noop transform', testGeneratorOutputPipe, 1, false, true, true);178test('Can use generators with subprocess.stdout, objectMode, noop transform', testGeneratorOutputPipe, 1, true, true, true);179test('Can use generators with subprocess.stdio[2], objectMode, noop transform', testGeneratorOutputPipe, 2, false, true, true);180test('Can use generators with subprocess.stderr, objectMode, noop transform', testGeneratorOutputPipe, 2, true, true, true);181test('Can use generators with subprocess.stdio[*] as output, objectMode, noop transform', testGeneratorOutputPipe, 3, false, true, true);182183const getAllStdioOption = (stdioOption, encoding, objectMode) => {184 if (stdioOption) {185 return 'pipe';
113 unmodified lines
299});300301test('Can use generators from a Readable stream', async t => {302 const passThrough = new PassThrough();303 const childProcess = execa('stdin-fd.js', ['0'], {stdin: [passThrough, uppercaseGenerator]});303 const subprocess = execa('stdin-fd.js', ['0'], {stdin: [passThrough, uppercaseGenerator]});304 passThrough.end(foobarString);305 const {stdout} = await childProcess;305 const {stdout} = await subprocess;306 t.is(stdout, foobarUppercase);307});308309test('Can use generators with "inherit"', async t => {
36 unmodified lines
modified:test/stdio/handle.js+3 added-3 removed
19 unmodified lines
20test('Cannot pass an empty array to stderr - sync', testEmptyArray, 2, 'stderr', execaSync);21test('Cannot pass an empty array to stdio[*] - sync', testEmptyArray, 3, 'stdio[3]', execaSync);2223const testNoPipeOption = async (t, stdioOption, fdNumber) => {24 const childProcess = execa('empty.js', getStdio(fdNumber, stdioOption));25 t.is(childProcess.stdio[fdNumber], null);26 await childProcess;24 const subprocess = execa('empty.js', getStdio(fdNumber, stdioOption));25 t.is(subprocess.stdio[fdNumber], null);26 await subprocess;27};2829test('stdin can be "ignore"', testNoPipeOption, 'ignore', 0);30test('stdin can be ["ignore"]', testNoPipeOption, ['ignore'], 0);
57 unmodified lines
modified:test/stdio/iterable.js+5 added-5 removed
106 unmodified lines
107test('stderr option cannot be an iterable - sync', testNoIterableOutput, stringGenerator(), 2, execaSync);108109test('stdin option can be an infinite iterable', async t => {110 const iterable = infiniteGenerator();111 const childProcess = execa('stdin.js', getStdio(0, iterable));112 await once(childProcess.stdout, 'data');113 childProcess.kill();114 const {stdout} = await t.throwsAsync(childProcess);111 const subprocess = execa('stdin.js', getStdio(0, iterable));112 await once(subprocess.stdout, 'data');113 subprocess.kill();114 const {stdout} = await t.throwsAsync(subprocess);115 t.true(stdout.startsWith('foo'));116 t.deepEqual(await iterable.next(), {value: undefined, done: true});117});118
4 unmodified lines
123124test('stdin option can be multiple iterables', testMultipleIterable, 0);125test('stdio[*] option can be multiple iterables', testMultipleIterable, 3);126127test('stdin option iterable is canceled on process error', async t => {127test('stdin option iterable is canceled on subprocess error', async t => {128 const iterable = infiniteGenerator();129 await t.throwsAsync(execa('stdin.js', {stdin: iterable, timeout: 1}), {message: /timed out/});130 // eslint-disable-next-line no-unused-vars, no-empty131 for await (const _ of iterable) {}
1 unmodified line
modified:test/stdio/lines.js+4 added-4 removed
203 unmodified lines
204 t.deepEqual(stdout, expectedLines);205});206207test('"lines: true" works with stream async iteration', async t => {208 const childProcess = execa('noop.js', {lines: true, stdout: getChunksGenerator(simpleChunk), buffer: false});209 const [stdout] = await Promise.all([childProcess.stdout.toArray(), childProcess]);208 const subprocess = execa('noop.js', {lines: true, stdout: getChunksGenerator(simpleChunk), buffer: false});209 const [stdout] = await Promise.all([subprocess.stdout.toArray(), subprocess]);210 t.deepEqual(stdout, simpleLines);211});212213test('"lines: true" works with stream "data" events', async t => {214 const childProcess = execa('noop.js', {lines: true, stdout: getChunksGenerator(simpleChunk), buffer: false});215 const [[firstLine]] = await Promise.all([once(childProcess.stdout, 'data'), childProcess]);214 const subprocess = execa('noop.js', {lines: true, stdout: getChunksGenerator(simpleChunk), buffer: false});215 const [[firstLine]] = await Promise.all([once(subprocess.stdout, 'data'), subprocess]);216 t.is(firstLine, simpleLines[0]);217});218219test('"lines: true" works with writable streams targets', async t => {
10 unmodified lines
modified:test/stdio/node-stream.js+28 added-28 removed
69 unmodified lines
70 await once(stream, 'open');71 return {stream, filePath};72};7374const assertFileStreamError = async (t, childProcess, stream, filePath) => {74const assertFileStreamError = async (t, subprocess, stream, filePath) => {75 const error = new Error('test');76 stream.destroy(error);7778 t.is(await t.throwsAsync(childProcess), error);78 t.is(await t.throwsAsync(subprocess), error);79 t.is(error.exitCode, 0);80 t.is(error.signal, undefined);8182 await rm(filePath);
18 unmodified lines
101const testFileReadableError = async (t, fdNumber) => {102 const {stream, filePath} = await createFileReadStream();103104 const fdNumberString = fdNumber === 'input' ? '0' : `${fdNumber}`;105 const childProcess = execa('stdin-fd.js', [fdNumberString], getStdio(fdNumber, stream));105 const subprocess = execa('stdin-fd.js', [fdNumberString], getStdio(fdNumber, stream));106107 await assertFileStreamError(t, childProcess, stream, filePath);107 await assertFileStreamError(t, subprocess, stream, filePath);108};109110test.serial('input handles errors from a Node.js Readable with a file descriptor', testFileReadableError, 'input');111test.serial('stdin handles errors from a Node.js Readable with a file descriptor', testFileReadableError, 0);
37 unmodified lines
149150const testFileWritableError = async (t, fdNumber) => {151 const {stream, filePath} = await createFileWriteStream();152153 const childProcess = execa('noop-stdin-fd.js', [`${fdNumber}`], getStdio(fdNumber, stream));154 childProcess.stdin.end(foobarString);153 const subprocess = execa('noop-stdin-fd.js', [`${fdNumber}`], getStdio(fdNumber, stream));154 subprocess.stdin.end(foobarString);155156 await assertFileStreamError(t, childProcess, stream, filePath);156 await assertFileStreamError(t, subprocess, stream, filePath);157};158159test.serial('stdout handles errors from a Node.js Writable with a file descriptor', testFileWritableError, 1);160test.serial('stderr handles errors from a Node.js Writable with a file descriptor', testFileWritableError, 2);
49 unmodified lines
210test('stdout can be [Writable, "pipe"] without a file descriptor', testLazyFileWritable, 1);211test('stderr can be [Writable, "pipe"] without a file descriptor', testLazyFileWritable, 2);212test('stdio[*] can be [Writable, "pipe"] without a file descriptor', testLazyFileWritable, 3);213214test('Waits for custom streams destroy on process errors', async t => {214test('Waits for custom streams destroy on subprocess errors', async t => {215 let waitedForDestroy = false;216 const stream = new Writable({217 destroy: callbackify(async error => {218 await setImmediate();
5 unmodified lines
224 t.true(timedOut);225 t.true(waitedForDestroy);226});227228test('Handles custom streams destroy errors on process success', async t => {228test('Handles custom streams destroy errors on subprocess success', async t => {229 const error = new Error('test');230 const stream = new Writable({231 destroy(destroyError, done) {232 done(destroyError ?? error);
7 unmodified lines
240 await t.throwsAsync(execa('noop.js', {[streamName]: [stream, 'pipe'], uid: -1}));241 t.true(stream.destroyed);242};243244test('Input streams are canceled on early process exit', testStreamEarlyExit, noopReadable(), 'stdin');245test('Output streams are canceled on early process exit', testStreamEarlyExit, noopWritable(), 'stdout');244test('Input streams are canceled on early subprocess exit', testStreamEarlyExit, noopReadable(), 'stdin');245test('Output streams are canceled on early subprocess exit', testStreamEarlyExit, noopWritable(), 'stdout');246247const testInputDuplexStream = async (t, fdNumber) => {248 const stream = new PassThrough();249 stream.end(foobarString);
20 unmodified lines
270const testInputStreamAbort = async (t, fdNumber) => {271 const stream = new PassThrough();272 stream.destroy();273274 const childProcess = execa('stdin-fd.js', [`${fdNumber}`], getStdio(fdNumber, [stream, new Uint8Array()]));275 await childProcess;276 t.true(childProcess.stdio[fdNumber].writableEnded);274 const subprocess = execa('stdin-fd.js', [`${fdNumber}`], getStdio(fdNumber, [stream, new Uint8Array()]));275 await subprocess;276 t.true(subprocess.stdio[fdNumber].writableEnded);277};278279test('childProcess.stdin is ended when an input stream aborts', testInputStreamAbort, 0);280test('childProcess.stdio[*] is ended when an input stream aborts', testInputStreamAbort, 3);279test('subprocess.stdin is ended when an input stream aborts', testInputStreamAbort, 0);280test('subprocess.stdio[*] is ended when an input stream aborts', testInputStreamAbort, 3);281282const testInputStreamError = async (t, fdNumber) => {283 const stream = new PassThrough();284 const error = new Error(foobarString);285 stream.destroy(error);286287 const childProcess = execa('stdin-fd.js', [`${fdNumber}`], getStdio(fdNumber, [stream, new Uint8Array()]));288 t.is(await t.throwsAsync(childProcess), error);289 t.true(childProcess.stdio[fdNumber].writableEnded);287 const subprocess = execa('stdin-fd.js', [`${fdNumber}`], getStdio(fdNumber, [stream, new Uint8Array()]));288 t.is(await t.throwsAsync(subprocess), error);289 t.true(subprocess.stdio[fdNumber].writableEnded);290};291292test('childProcess.stdin is ended when an input stream errors', testInputStreamError, 0);293test('childProcess.stdio[*] is ended when an input stream errors', testInputStreamError, 3);292test('subprocess.stdin is ended when an input stream errors', testInputStreamError, 0);293test('subprocess.stdio[*] is ended when an input stream errors', testInputStreamError, 3);294295const testOutputStreamError = async (t, fdNumber) => {296 const stream = new PassThrough();297 const error = new Error(foobarString);298 stream.destroy(error);299300 const childProcess = execa('noop-fd.js', [`${fdNumber}`], getStdio(fdNumber, [stream, 'pipe']));301 t.is(await t.throwsAsync(childProcess), error);302 t.true(childProcess.stdio[fdNumber].readableAborted);303 t.is(childProcess.stdio[fdNumber].errored, null);300 const subprocess = execa('noop-fd.js', [`${fdNumber}`], getStdio(fdNumber, [stream, 'pipe']));301 t.is(await t.throwsAsync(subprocess), error);302 t.true(subprocess.stdio[fdNumber].readableAborted);303 t.is(subprocess.stdio[fdNumber].errored, null);304};305306test('childProcess.stdout is aborted when an output stream errors', testOutputStreamError, 1);307test('childProcess.stderr is aborted when an output stream errors', testOutputStreamError, 2);308test('childProcess.stdio[*] is aborted when an output stream errors', testOutputStreamError, 3);306test('subprocess.stdout is aborted when an output stream errors', testOutputStreamError, 1);307test('subprocess.stderr is aborted when an output stream errors', testOutputStreamError, 2);308test('subprocess.stdio[*] is aborted when an output stream errors', testOutputStreamError, 3);
modified:test/stdio/pipeline.js+15 added-15 removed
4 unmodified lines
56setFixtureDir();78const testDestroyStandard = async (t, fdNumber) => {9 const childProcess = execa('forever.js', {...getStdio(fdNumber, [STANDARD_STREAMS[fdNumber], 'pipe']), timeout: 1});10 await t.throwsAsync(childProcess, {message: /timed out/});9 const subprocess = execa('forever.js', {...getStdio(fdNumber, [STANDARD_STREAMS[fdNumber], 'pipe']), timeout: 1});10 await t.throwsAsync(subprocess, {message: /timed out/});11 t.false(STANDARD_STREAMS[fdNumber].destroyed);12};1314test('Does not destroy process.stdin on child process errors', testDestroyStandard, 0);15test('Does not destroy process.stdout on child process errors', testDestroyStandard, 1);16test('Does not destroy process.stderr on child process errors', testDestroyStandard, 2);14test('Does not destroy process.stdin on subprocess errors', testDestroyStandard, 0);15test('Does not destroy process.stdout on subprocess errors', testDestroyStandard, 1);16test('Does not destroy process.stderr on subprocess errors', testDestroyStandard, 2);1718const testDestroyStandardSpawn = async (t, fdNumber) => {19 await t.throwsAsync(execa('forever.js', {...getStdio(fdNumber, [STANDARD_STREAMS[fdNumber], 'pipe']), uid: -1}));20 t.false(STANDARD_STREAMS[fdNumber].destroyed);21};2223test('Does not destroy process.stdin on spawn process errors', testDestroyStandardSpawn, 0);24test('Does not destroy process.stdout on spawn process errors', testDestroyStandardSpawn, 1);25test('Does not destroy process.stderr on spawn process errors', testDestroyStandardSpawn, 2);23test('Does not destroy process.stdin on subprocess early errors', testDestroyStandardSpawn, 0);24test('Does not destroy process.stdout on subprocess early errors', testDestroyStandardSpawn, 1);25test('Does not destroy process.stderr on subprocess early errors', testDestroyStandardSpawn, 2);2627const testDestroyStandardStream = async (t, fdNumber) => {28 const childProcess = execa('forever.js', getStdio(fdNumber, [STANDARD_STREAMS[fdNumber], 'pipe']));28 const subprocess = execa('forever.js', getStdio(fdNumber, [STANDARD_STREAMS[fdNumber], 'pipe']));29 const error = new Error('test');30 childProcess.stdio[fdNumber].destroy(error);31 childProcess.kill();32 const thrownError = await t.throwsAsync(childProcess);30 subprocess.stdio[fdNumber].destroy(error);31 subprocess.kill();32 const thrownError = await t.throwsAsync(subprocess);33 t.is(thrownError, error);34 t.false(STANDARD_STREAMS[fdNumber].destroyed);35};3637test('Does not destroy process.stdin on stream process errors', testDestroyStandardStream, 0);38test('Does not destroy process.stdout on stream process errors', testDestroyStandardStream, 1);39test('Does not destroy process.stderr on stream process errors', testDestroyStandardStream, 2);37test('Does not destroy process.stdin on stream subprocess errors', testDestroyStandardStream, 0);38test('Does not destroy process.stdout on stream subprocess errors', testDestroyStandardStream, 1);39test('Does not destroy process.stderr on stream subprocess errors', testDestroyStandardStream, 2);
modified:test/stdio/transform.js+22 added-22 removed
103 unmodified lines
104 }105};106107const testManyYields = async (t, final) => {108 const childProcess = execa('noop.js', {stdout: convertTransformToFinal(manyYieldGenerator, final), buffer: false});109 const [chunks] = await Promise.all([getStreamAsArray(childProcess.stdout), childProcess]);108 const subprocess = execa('noop.js', {stdout: convertTransformToFinal(manyYieldGenerator, final), buffer: false});109 const [chunks] = await Promise.all([getStreamAsArray(subprocess.stdout), subprocess]);110 const expectedChunk = Buffer.alloc(getDefaultHighWaterMark(false) * chunksPerCall).fill('\n');111 t.deepEqual(chunks, Array.from({length: callCount}).fill(expectedChunk));112};113
47 unmodified lines
161 {message: GENERATOR_ERROR_REGEXP},162 );163};164165test('Generators "transform" errors make process fail', testThrowingGenerator, false);166test('Generators "final" errors make process fail', testThrowingGenerator, true);165test('Generators "transform" errors make subprocess fail', testThrowingGenerator, false);166test('Generators "final" errors make subprocess fail', testThrowingGenerator, true);167168test('Generators errors make process fail even when other output generators do not throw', async t => {168test('Generators errors make subprocess fail even when other output generators do not throw', async t => {169 await t.throwsAsync(170 execa('noop-fd.js', ['1', foobarString], {stdout: [noopGenerator(false), throwingGenerator, noopGenerator(false)]}),171 {message: GENERATOR_ERROR_REGEXP},172 );173});174175test('Generators errors make process fail even when other input generators do not throw', async t => {176 const childProcess = execa('stdin-fd.js', ['0'], {stdin: [noopGenerator(false), throwingGenerator, noopGenerator(false)]});177 childProcess.stdin.write('foobar\n');178 await t.throwsAsync(childProcess, {message: GENERATOR_ERROR_REGEXP});175test('Generators errors make subprocess fail even when other input generators do not throw', async t => {176 const subprocess = execa('stdin-fd.js', ['0'], {stdin: [noopGenerator(false), throwingGenerator, noopGenerator(false)]});177 subprocess.stdin.write('foobar\n');178 await t.throwsAsync(subprocess, {message: GENERATOR_ERROR_REGEXP});179});180181const testGeneratorCancel = async (t, error) => {182 const childProcess = execa('noop.js', {stdout: infiniteGenerator});183 await once(childProcess.stdout, 'data');184 childProcess.stdout.destroy(error);185 await (error === undefined ? t.notThrowsAsync(childProcess) : t.throwsAsync(childProcess));182 const subprocess = execa('noop.js', {stdout: infiniteGenerator});183 await once(subprocess.stdout, 'data');184 subprocess.stdout.destroy(error);185 await (error === undefined ? t.notThrowsAsync(subprocess) : t.throwsAsync(subprocess));186};187188test('Running generators are canceled on process abort', testGeneratorCancel, undefined);189test('Running generators are canceled on process error', testGeneratorCancel, new Error('test'));188test('Running generators are canceled on subprocess abort', testGeneratorCancel, undefined);189test('Running generators are canceled on subprocess error', testGeneratorCancel, new Error('test'));190191const testGeneratorDestroy = async (t, transform) => {192 const childProcess = execa('forever.js', {stdout: transform});192 const subprocess = execa('forever.js', {stdout: transform});193 const error = new Error('test');194 childProcess.stdout.destroy(error);195 childProcess.kill();196 t.is(await t.throwsAsync(childProcess), error);194 subprocess.stdout.destroy(error);195 subprocess.kill();196 t.is(await t.throwsAsync(subprocess), error);197};198199test('Generators are destroyed on process error, sync', testGeneratorDestroy, noopGenerator(false));200test('Generators are destroyed on process error, async', testGeneratorDestroy, infiniteGenerator);199test('Generators are destroyed on subprocess error, sync', testGeneratorDestroy, noopGenerator(false));200test('Generators are destroyed on subprocess error, async', testGeneratorDestroy, infiniteGenerator);201202test('Generators are destroyed on early process exit', async t => {202test('Generators are destroyed on early subprocess exit', async t => {203 await t.throwsAsync(execa('noop.js', {stdout: infiniteGenerator, uid: -1}));204});
modified:test/stdio/validate.js+4 added-4 removed
7 unmodified lines
8setFixtureDir();910// eslint-disable-next-line max-params11const testGeneratorReturn = async (t, fdNumber, generators, fixtureName, isNull) => {12 const childProcess = execa(fixtureName, [`${fdNumber}`], getStdio(fdNumber, generators));12 const subprocess = execa(fixtureName, [`${fdNumber}`], getStdio(fdNumber, generators));13 const message = isNull ? /not be called at all/ : /a string or an Uint8Array/;14 await t.throwsAsync(childProcess, {message});14 await t.throwsAsync(subprocess, {message});15};1617const lastInputGenerator = (input, objectMode) => [foobarUint8Array, getOutputGenerator(input, objectMode)];18const inputGenerator = (input, objectMode) => [...lastInputGenerator(input, objectMode), serializeGenerator];
14 unmodified lines
33test('Generators with result.stdout cannot return undefined if not in objectMode', testGeneratorReturn, 1, getOutputGenerator(undefined, false), 'noop-fd.js', true);34test('Generators with result.stdout cannot return undefined if in objectMode', testGeneratorReturn, 1, getOutputGenerator(undefined, true), 'noop-fd.js', true);3536test('Generators "final" return value is validated', async t => {37 const childProcess = execa('noop.js', {stdout: convertTransformToFinal(getOutputGenerator(null, true), true)});38 await t.throwsAsync(childProcess, {message: /not be called at all/});37 const subprocess = execa('noop.js', {stdout: convertTransformToFinal(getOutputGenerator(null, true), true)});38 await t.throwsAsync(subprocess, {message: /not be called at all/});39});
modified:test/stdio/web-stream.js+1 added-1 removed
86 unmodified lines
8788test('stdin option handles errors in ReadableStream', testReadableStreamError, 0);89test('stdio[*] option handles errors in ReadableStream', testReadableStreamError, 3);9091test('ReadableStream with stdin is canceled on process exit', async t => {91test('ReadableStream with stdin is canceled on subprocess exit', async t => {92 let readableStream;93 const promise = new Promise(resolve => {94 readableStream = new ReadableStream({cancel: resolve});95 });
3 unmodified lines
modified:test/stream/all.js+19 added-19 removed
19 unmodified lines
20 t.is(all, undefined);21});2223const testAllProperties = async (t, options) => {24 const childProcess = execa('empty.js', {...options, all: true});25 t.is(childProcess.all.readableObjectMode, false);26 t.is(childProcess.all.readableHighWaterMark, getDefaultHighWaterMark(false));27 await childProcess;24 const subprocess = execa('empty.js', {...options, all: true});25 t.is(subprocess.all.readableObjectMode, false);26 t.is(subprocess.all.readableHighWaterMark, getDefaultHighWaterMark(false));27 await subprocess;28};2930test('childProcess.all has the right objectMode and highWaterMark - stdout + stderr', testAllProperties, {});31test('childProcess.all has the right objectMode and highWaterMark - stdout only', testAllProperties, {stderr: 'ignore'});32test('childProcess.all has the right objectMode and highWaterMark - stderr only', testAllProperties, {stdout: 'ignore'});30test('subprocess.all has the right objectMode and highWaterMark - stdout + stderr', testAllProperties, {});31test('subprocess.all has the right objectMode and highWaterMark - stdout only', testAllProperties, {stderr: 'ignore'});32test('subprocess.all has the right objectMode and highWaterMark - stderr only', testAllProperties, {stdout: 'ignore'});3334const testAllIgnore = async (t, streamName, otherStreamName) => {35 const childProcess = execa('noop-both.js', {[otherStreamName]: 'ignore', all: true});36 t.is(childProcess[otherStreamName], null);37 t.not(childProcess[streamName], null);38 t.not(childProcess.all, null);39 t.is(childProcess.all.readableObjectMode, childProcess[streamName].readableObjectMode);40 t.is(childProcess.all.readableHighWaterMark, childProcess[streamName].readableHighWaterMark);35 const subprocess = execa('noop-both.js', {[otherStreamName]: 'ignore', all: true});36 t.is(subprocess[otherStreamName], null);37 t.not(subprocess[streamName], null);38 t.not(subprocess.all, null);39 t.is(subprocess.all.readableObjectMode, subprocess[streamName].readableObjectMode);40 t.is(subprocess.all.readableHighWaterMark, subprocess[streamName].readableHighWaterMark);4142 const result = await childProcess;42 const result = await subprocess;43 t.is(result[otherStreamName], undefined);44 t.is(result[streamName], 'foobar');45 t.is(result.all, 'foobar');46};
1 unmodified line
48test('can use all: true with stdout: ignore', testAllIgnore, 'stderr', 'stdout');49test('can use all: true with stderr: ignore', testAllIgnore, 'stdout', 'stderr');5051test('can use all: true with stdout: ignore + stderr: ignore', async t => {52 const childProcess = execa('noop-both.js', {stdout: 'ignore', stderr: 'ignore', all: true});53 t.is(childProcess.stdout, null);54 t.is(childProcess.stderr, null);55 t.is(childProcess.all, undefined);52 const subprocess = execa('noop-both.js', {stdout: 'ignore', stderr: 'ignore', all: true});53 t.is(subprocess.stdout, null);54 t.is(subprocess.stderr, null);55 t.is(subprocess.all, undefined);5657 const {stdout, stderr, all} = await childProcess;57 const {stdout, stderr, all} = await subprocess;58 t.is(stdout, undefined);59 t.is(stderr, undefined);60 t.is(all, undefined);61});
deleted:test/stream/child.js-118 removed
1import {platform} from 'node:process';2import {setTimeout} from 'node:timers/promises';3import test from 'ava';4import {execa} from '../../index.js';5import {setFixtureDir} from '../helpers/fixtures-dir.js';6import {fullStdio, getStdio, prematureClose} from '../helpers/stdio.js';7import {infiniteGenerator} from '../helpers/generator.js';89setFixtureDir();1011const isWindows = platform === 'win32';1213const getStreamInputProcess = fdNumber => execa('stdin-fd.js', [`${fdNumber}`], fdNumber === 314 ? getStdio(3, [new Uint8Array(), infiniteGenerator])15 : {});16const getStreamOutputProcess = fdNumber => execa('noop-repeat.js', [`${fdNumber}`], fdNumber === 3 ? fullStdio : {});1718const assertStreamInputError = (t, {exitCode, signal, isTerminated, failed}) => {19 t.is(exitCode, 0);20 t.is(signal, undefined);21 t.false(isTerminated);22 t.true(failed);23};2425const assertStreamOutputError = (t, fdNumber, {exitCode, signal, isTerminated, failed, stderr}) => {26 if (fdNumber !== 3) {27 t.is(exitCode, 1);28 }2930 t.is(signal, undefined);31 t.false(isTerminated);32 t.true(failed);3334 if (fdNumber === 1 && !isWindows) {35 t.true(stderr.includes('EPIPE'));36 }37};3839const testStreamInputAbort = async (t, fdNumber) => {40 const childProcess = getStreamInputProcess(fdNumber);41 childProcess.stdio[fdNumber].destroy();42 const error = await t.throwsAsync(childProcess, prematureClose);43 assertStreamInputError(t, error);44};4546test('Aborting stdin should not make the process exit', testStreamInputAbort, 0);47test('Aborting input stdio[*] should not make the process exit', testStreamInputAbort, 3);4849const testStreamOutputAbort = async (t, fdNumber) => {50 const childProcess = getStreamOutputProcess(fdNumber);51 childProcess.stdio[fdNumber].destroy();52 const error = await t.throwsAsync(childProcess);53 assertStreamOutputError(t, fdNumber, error);54};5556test('Aborting stdout should not make the process exit', testStreamOutputAbort, 1);57test('Aborting stderr should not make the process exit', testStreamOutputAbort, 2);58test('Aborting output stdio[*] should not make the process exit', testStreamOutputAbort, 3);5960const testStreamInputDestroy = async (t, fdNumber) => {61 const childProcess = getStreamInputProcess(fdNumber);62 const error = new Error('test');63 childProcess.stdio[fdNumber].destroy(error);64 t.is(await t.throwsAsync(childProcess), error);65 assertStreamInputError(t, error);66};6768test('Destroying stdin should not make the process exit', testStreamInputDestroy, 0);69test('Destroying input stdio[*] should not make the process exit', testStreamInputDestroy, 3);7071const testStreamOutputDestroy = async (t, fdNumber) => {72 const childProcess = getStreamOutputProcess(fdNumber);73 const error = new Error('test');74 childProcess.stdio[fdNumber].destroy(error);75 t.is(await t.throwsAsync(childProcess), error);76 assertStreamOutputError(t, fdNumber, error);77};7879test('Destroying stdout should not make the process exit', testStreamOutputDestroy, 1);80test('Destroying stderr should not make the process exit', testStreamOutputDestroy, 2);81test('Destroying output stdio[*] should not make the process exit', testStreamOutputDestroy, 3);8283const testStreamInputError = async (t, fdNumber) => {84 const childProcess = getStreamInputProcess(fdNumber);85 const error = new Error('test');86 const stream = childProcess.stdio[fdNumber];87 stream.emit('error', error);88 stream.end();89 t.is(await t.throwsAsync(childProcess), error);90 assertStreamInputError(t, error);91};9293test('Errors on stdin should not make the process exit', testStreamInputError, 0);94test('Errors on input stdio[*] should not make the process exit', testStreamInputError, 3);9596const testStreamOutputError = async (t, fdNumber) => {97 const childProcess = getStreamOutputProcess(fdNumber);98 const error = new Error('test');99 const stream = childProcess.stdio[fdNumber];100 stream.emit('error', error);101 t.is(await t.throwsAsync(childProcess), error);102 assertStreamOutputError(t, fdNumber, error);103};104105test('Errors on stdout should not make the process exit', testStreamOutputError, 1);106test('Errors on stderr should not make the process exit', testStreamOutputError, 2);107test('Errors on output stdio[*] should not make the process exit', testStreamOutputError, 3);108109const testWaitOnStreamEnd = async (t, fdNumber) => {110 const childProcess = execa('stdin-fd.js', [`${fdNumber}`], fullStdio);111 await setTimeout(100);112 childProcess.stdio[fdNumber].end('foobar');113 const {stdout} = await childProcess;114 t.is(stdout, 'foobar');115};116117test('Process waits on stdin before exiting', testWaitOnStreamEnd, 0);118test('Process waits on stdio[*] before exiting', testWaitOnStreamEnd, 3);
modified:test/stream/exit.js+34 added-34 removed
9 unmodified lines
10const testBufferIgnore = async (t, fdNumber, all) => {11 await t.notThrowsAsync(execa('max-buffer.js', [`${fdNumber}`], {...getStdio(fdNumber, 'ignore'), buffer: false, all}));12};1314test('Process buffers stdout, which does not prevent exit if ignored', testBufferIgnore, 1, false);15test('Process buffers stderr, which does not prevent exit if ignored', testBufferIgnore, 2, false);16test('Process buffers all, which does not prevent exit if ignored', testBufferIgnore, 1, true);14test('Subprocess buffers stdout, which does not prevent exit if ignored', testBufferIgnore, 1, false);15test('Subprocess buffers stderr, which does not prevent exit if ignored', testBufferIgnore, 2, false);16test('Subprocess buffers all, which does not prevent exit if ignored', testBufferIgnore, 1, true);1718const testBufferNotRead = async (t, fdNumber, all) => {19 const subprocess = execa('max-buffer.js', [`${fdNumber}`], {...fullStdio, buffer: false, all});20 await t.notThrowsAsync(subprocess);21};2223test('Process buffers stdout, which does not prevent exit if not read and buffer is false', testBufferNotRead, 1, false);24test('Process buffers stderr, which does not prevent exit if not read and buffer is false', testBufferNotRead, 2, false);25test('Process buffers stdio[*], which does not prevent exit if not read and buffer is false', testBufferNotRead, 3, false);26test('Process buffers all, which does not prevent exit if not read and buffer is false', testBufferNotRead, 1, true);23test('Subprocess buffers stdout, which does not prevent exit if not read and buffer is false', testBufferNotRead, 1, false);24test('Subprocess buffers stderr, which does not prevent exit if not read and buffer is false', testBufferNotRead, 2, false);25test('Subprocess buffers stdio[*], which does not prevent exit if not read and buffer is false', testBufferNotRead, 3, false);26test('Subprocess buffers all, which does not prevent exit if not read and buffer is false', testBufferNotRead, 1, true);2728const testBufferRead = async (t, fdNumber, all) => {29 const subprocess = execa('max-buffer.js', [`${fdNumber}`], {...fullStdio, buffer: false, all});30 const stream = all ? subprocess.all : subprocess.stdio[fdNumber];31 stream.resume();32 await t.notThrowsAsync(subprocess);33};3435test('Process buffers stdout, which does not prevent exit if read and buffer is false', testBufferRead, 1, false);36test('Process buffers stderr, which does not prevent exit if read and buffer is false', testBufferRead, 2, false);37test('Process buffers stdio[*], which does not prevent exit if read and buffer is false', testBufferRead, 3, false);38test('Process buffers all, which does not prevent exit if read and buffer is false', testBufferRead, 1, true);35test('Subprocess buffers stdout, which does not prevent exit if read and buffer is false', testBufferRead, 1, false);36test('Subprocess buffers stderr, which does not prevent exit if read and buffer is false', testBufferRead, 2, false);37test('Subprocess buffers stdio[*], which does not prevent exit if read and buffer is false', testBufferRead, 3, false);38test('Subprocess buffers all, which does not prevent exit if read and buffer is false', testBufferRead, 1, true);3940const testBufferExit = async (t, fdNumber, fixtureName, reject) => {41 const childProcess = execa(fixtureName, [`${fdNumber}`], {...fullStdio, reject});41 const subprocess = execa(fixtureName, [`${fdNumber}`], {...fullStdio, reject});42 await setTimeout(100);43 const {stdio} = await childProcess;43 const {stdio} = await subprocess;44 t.is(stdio[fdNumber], 'foobar');45};4647test('Process buffers stdout before it is read', testBufferExit, 1, 'noop-delay.js', true);48test('Process buffers stderr before it is read', testBufferExit, 2, 'noop-delay.js', true);49test('Process buffers stdio[*] before it is read', testBufferExit, 3, 'noop-delay.js', true);50test('Process buffers stdout right away, on successfully exit', testBufferExit, 1, 'noop-fd.js', true);51test('Process buffers stderr right away, on successfully exit', testBufferExit, 2, 'noop-fd.js', true);52test('Process buffers stdio[*] right away, on successfully exit', testBufferExit, 3, 'noop-fd.js', true);53test('Process buffers stdout right away, on failure', testBufferExit, 1, 'noop-fail.js', false);54test('Process buffers stderr right away, on failure', testBufferExit, 2, 'noop-fail.js', false);55test('Process buffers stdio[*] right away, on failure', testBufferExit, 3, 'noop-fail.js', false);47test('Subprocess buffers stdout before it is read', testBufferExit, 1, 'noop-delay.js', true);48test('Subprocess buffers stderr before it is read', testBufferExit, 2, 'noop-delay.js', true);49test('Subprocess buffers stdio[*] before it is read', testBufferExit, 3, 'noop-delay.js', true);50test('Subprocess buffers stdout right away, on successfully exit', testBufferExit, 1, 'noop-fd.js', true);51test('Subprocess buffers stderr right away, on successfully exit', testBufferExit, 2, 'noop-fd.js', true);52test('Subprocess buffers stdio[*] right away, on successfully exit', testBufferExit, 3, 'noop-fd.js', true);53test('Subprocess buffers stdout right away, on failure', testBufferExit, 1, 'noop-fail.js', false);54test('Subprocess buffers stderr right away, on failure', testBufferExit, 2, 'noop-fail.js', false);55test('Subprocess buffers stdio[*] right away, on failure', testBufferExit, 3, 'noop-fail.js', false);5657const testBufferDirect = async (t, fdNumber) => {58 const childProcess = execa('noop-fd.js', [`${fdNumber}`], fullStdio);59 const data = await once(childProcess.stdio[fdNumber], 'data');58 const subprocess = execa('noop-fd.js', [`${fdNumber}`], fullStdio);59 const data = await once(subprocess.stdio[fdNumber], 'data');60 t.is(data.toString().trim(), 'foobar');61 const result = await childProcess;61 const result = await subprocess;62 t.is(result.stdio[fdNumber], 'foobar');63};6465test('Process buffers stdout right away, even if directly read', testBufferDirect, 1);66test('Process buffers stderr right away, even if directly read', testBufferDirect, 2);67test('Process buffers stdio[*] right away, even if directly read', testBufferDirect, 3);65test('Subprocess buffers stdout right away, even if directly read', testBufferDirect, 1);66test('Subprocess buffers stderr right away, even if directly read', testBufferDirect, 2);67test('Subprocess buffers stdio[*] right away, even if directly read', testBufferDirect, 3);6869const testBufferDestroyOnEnd = async (t, fdNumber) => {70 const childProcess = execa('noop-fd.js', [`${fdNumber}`], fullStdio);71 const result = await childProcess;70 const subprocess = execa('noop-fd.js', [`${fdNumber}`], fullStdio);71 const result = await subprocess;72 t.is(result.stdio[fdNumber], 'foobar');73 t.true(childProcess.stdio[fdNumber].destroyed);73 t.true(subprocess.stdio[fdNumber].destroyed);74};7576test('childProcess.stdout must be read right away', testBufferDestroyOnEnd, 1);77test('childProcess.stderr must be read right away', testBufferDestroyOnEnd, 2);78test('childProcess.stdio[*] must be read right away', testBufferDestroyOnEnd, 3);76test('subprocess.stdout must be read right away', testBufferDestroyOnEnd, 1);77test('subprocess.stderr must be read right away', testBufferDestroyOnEnd, 2);78test('subprocess.stdio[*] must be read right away', testBufferDestroyOnEnd, 3);
modified:test/stream/max-buffer.js+3 added-3 removed
94 unmodified lines
95test('do not hit maxBuffer when `buffer` is `false` with stderr', testNoMaxBufferOption, 2);96test('do not hit maxBuffer when `buffer` is `false` with stdio[*]', testNoMaxBufferOption, 3);9798const testMaxBufferAbort = async (t, fdNumber) => {99 const childProcess = execa('max-buffer.js', [`${fdNumber}`, `${maxBuffer + 1}`], {...fullStdio, maxBuffer});99 const subprocess = execa('max-buffer.js', [`${fdNumber}`, `${maxBuffer + 1}`], {...fullStdio, maxBuffer});100 await Promise.all([101 t.throwsAsync(childProcess, {message: /maxBuffer exceeded/}),102 t.throwsAsync(getStream(childProcess.stdio[fdNumber]), {code: 'ABORT_ERR'}),101 t.throwsAsync(subprocess, {message: /maxBuffer exceeded/}),102 t.throwsAsync(getStream(subprocess.stdio[fdNumber]), {code: 'ABORT_ERR'}),103 ]);104};105106test('abort stream when hitting maxBuffer with stdout', testMaxBufferAbort, 1);
2 unmodified lines
modified:test/stream/no-buffer.js+4 added-4 removed
42 unmodified lines
43 getOutput(subprocess.stdio[fdNumber]),44 all ? getOutput(subprocess.all) : undefined,45 ]);4647 const expectedProcessResult = buffer ? foobarString : undefined;47 const expectedResult = buffer ? foobarString : undefined;48 const expectedOutput = !buffer || useDataEvents ? foobarString : '';4950 t.is(result.stdio[fdNumber], expectedProcessResult);50 t.is(result.stdio[fdNumber], expectedResult);51 t.is(output, expectedOutput);5253 if (all) {54 t.is(result.all, expectedProcessResult);54 t.is(result.all, expectedResult);55 t.is(allOutput, expectedOutput);56 }57};58
30 unmodified lines
89test('buffer: false > promise resolves', async t => {90 await t.notThrowsAsync(execa('noop.js', {buffer: false}));91});9293test('buffer: false > promise rejects when process returns non-zero', async t => {93test('buffer: false > promise rejects when subprocess returns non-zero', async t => {94 const {exitCode} = await t.throwsAsync(execa('fail.js', {buffer: false}));95 t.is(exitCode, 2);96});97
14 unmodified lines
modified:test/stream/resolve.js+7 added-7 removed
15 unmodified lines
16test('stdout is undefined if ignored - sync', testIgnore, 1, execaSync);17test('stderr is undefined if ignored - sync', testIgnore, 2, execaSync);18test('stdio[*] is undefined if ignored - sync', testIgnore, 3, execaSync);1920const testProcessEventsCleanup = async (t, fixtureName) => {21 const childProcess = execa(fixtureName, {reject: false});22 t.deepEqual(childProcess.eventNames().map(String).sort(), ['Symbol(error)', 'error', 'exit', 'spawn']);23 await childProcess;24 t.deepEqual(childProcess.eventNames(), []);20const testSubprocessEventsCleanup = async (t, fixtureName) => {21 const subprocess = execa(fixtureName, {reject: false});22 t.deepEqual(subprocess.eventNames().map(String).sort(), ['Symbol(error)', 'error', 'exit', 'spawn']);23 await subprocess;24 t.deepEqual(subprocess.eventNames(), []);25};2627test('childProcess listeners are cleaned up on success', testProcessEventsCleanup, 'empty.js');28test('childProcess listeners are cleaned up on failure', testProcessEventsCleanup, 'fail.js');27test('subprocess listeners are cleaned up on success', testSubprocessEventsCleanup, 'empty.js');28test('subprocess listeners are cleaned up on failure', testSubprocessEventsCleanup, 'fail.js');2930test('Aborting stdout should not abort stderr nor all', async t => {31 const subprocess = execa('empty.js', {all: true});32
17 unmodified lines
added:test/stream/subprocess.js+118 added
1import {platform} from 'node:process';2import {setTimeout} from 'node:timers/promises';3import test from 'ava';4import {execa} from '../../index.js';5import {setFixtureDir} from '../helpers/fixtures-dir.js';6import {fullStdio, getStdio, prematureClose} from '../helpers/stdio.js';7import {infiniteGenerator} from '../helpers/generator.js';89setFixtureDir();1011const isWindows = platform === 'win32';1213const getStreamInputSubprocess = fdNumber => execa('stdin-fd.js', [`${fdNumber}`], fdNumber === 314 ? getStdio(3, [new Uint8Array(), infiniteGenerator])15 : {});16const getStreamOutputSubprocess = fdNumber => execa('noop-repeat.js', [`${fdNumber}`], fdNumber === 3 ? fullStdio : {});1718const assertStreamInputError = (t, {exitCode, signal, isTerminated, failed}) => {19 t.is(exitCode, 0);20 t.is(signal, undefined);21 t.false(isTerminated);22 t.true(failed);23};2425const assertStreamOutputError = (t, fdNumber, {exitCode, signal, isTerminated, failed, stderr}) => {26 if (fdNumber !== 3) {27 t.is(exitCode, 1);28 }2930 t.is(signal, undefined);31 t.false(isTerminated);32 t.true(failed);3334 if (fdNumber === 1 && !isWindows) {35 t.true(stderr.includes('EPIPE'));36 }37};3839const testStreamInputAbort = async (t, fdNumber) => {40 const subprocess = getStreamInputSubprocess(fdNumber);41 subprocess.stdio[fdNumber].destroy();42 const error = await t.throwsAsync(subprocess, prematureClose);43 assertStreamInputError(t, error);44};4546test('Aborting stdin should not make the subprocess exit', testStreamInputAbort, 0);47test('Aborting input stdio[*] should not make the subprocess exit', testStreamInputAbort, 3);4849const testStreamOutputAbort = async (t, fdNumber) => {50 const subprocess = getStreamOutputSubprocess(fdNumber);51 subprocess.stdio[fdNumber].destroy();52 const error = await t.throwsAsync(subprocess);53 assertStreamOutputError(t, fdNumber, error);54};5556test('Aborting stdout should not make the subprocess exit', testStreamOutputAbort, 1);57test('Aborting stderr should not make the subprocess exit', testStreamOutputAbort, 2);58test('Aborting output stdio[*] should not make the subprocess exit', testStreamOutputAbort, 3);5960const testStreamInputDestroy = async (t, fdNumber) => {61 const subprocess = getStreamInputSubprocess(fdNumber);62 const error = new Error('test');63 subprocess.stdio[fdNumber].destroy(error);64 t.is(await t.throwsAsync(subprocess), error);65 assertStreamInputError(t, error);66};6768test('Destroying stdin should not make the subprocess exit', testStreamInputDestroy, 0);69test('Destroying input stdio[*] should not make the subprocess exit', testStreamInputDestroy, 3);7071const testStreamOutputDestroy = async (t, fdNumber) => {72 const subprocess = getStreamOutputSubprocess(fdNumber);73 const error = new Error('test');74 subprocess.stdio[fdNumber].destroy(error);75 t.is(await t.throwsAsync(subprocess), error);76 assertStreamOutputError(t, fdNumber, error);77};7879test('Destroying stdout should not make the subprocess exit', testStreamOutputDestroy, 1);80test('Destroying stderr should not make the subprocess exit', testStreamOutputDestroy, 2);81test('Destroying output stdio[*] should not make the subprocess exit', testStreamOutputDestroy, 3);8283const testStreamInputError = async (t, fdNumber) => {84 const subprocess = getStreamInputSubprocess(fdNumber);85 const error = new Error('test');86 const stream = subprocess.stdio[fdNumber];87 stream.emit('error', error);88 stream.end();89 t.is(await t.throwsAsync(subprocess), error);90 assertStreamInputError(t, error);91};9293test('Errors on stdin should not make the subprocess exit', testStreamInputError, 0);94test('Errors on input stdio[*] should not make the subprocess exit', testStreamInputError, 3);9596const testStreamOutputError = async (t, fdNumber) => {97 const subprocess = getStreamOutputSubprocess(fdNumber);98 const error = new Error('test');99 const stream = subprocess.stdio[fdNumber];100 stream.emit('error', error);101 t.is(await t.throwsAsync(subprocess), error);102 assertStreamOutputError(t, fdNumber, error);103};104105test('Errors on stdout should not make the subprocess exit', testStreamOutputError, 1);106test('Errors on stderr should not make the subprocess exit', testStreamOutputError, 2);107test('Errors on output stdio[*] should not make the subprocess exit', testStreamOutputError, 3);108109const testWaitOnStreamEnd = async (t, fdNumber) => {110 const subprocess = execa('stdin-fd.js', [`${fdNumber}`], fullStdio);111 await setTimeout(100);112 subprocess.stdio[fdNumber].end('foobar');113 const {stdout} = await subprocess;114 t.is(stdout, 'foobar');115};116117test('Subprocess waits on stdin before exiting', testWaitOnStreamEnd, 0);118test('Subprocess waits on stdio[*] before exiting', testWaitOnStreamEnd, 3);
modified:test/stream/wait.js+75 added-75 removed
20 unmodified lines
21const destroyOptionStream = ({stream, error}) => {22 stream.destroy(error);23};2425const destroyChildStream = ({childProcess, fdNumber, error}) => {26 childProcess.stdio[fdNumber].destroy(error);25const destroySubprocessStream = ({subprocess, fdNumber, error}) => {26 subprocess.stdio[fdNumber].destroy(error);27};2829const getStreamStdio = (fdNumber, stream, useTransform) => getStdio(fdNumber, [stream, useTransform ? noopGenerator(false) : 'pipe']);3031// eslint-disable-next-line max-params32const testStreamAbortWait = async (t, streamMethod, stream, fdNumber, useTransform) => {33 const childProcess = execa('noop-stdin-fd.js', [`${fdNumber}`], getStreamStdio(fdNumber, stream, useTransform));34 streamMethod({stream, childProcess, fdNumber});35 childProcess.stdin.end();33 const subprocess = execa('noop-stdin-fd.js', [`${fdNumber}`], getStreamStdio(fdNumber, stream, useTransform));34 streamMethod({stream, subprocess, fdNumber});35 subprocess.stdin.end();36 await setImmediate();37 stream.destroy();3839 const {stdout} = await childProcess;39 const {stdout} = await subprocess;40 t.is(stdout, '');41 t.true(stream.destroyed);42};4344test('Keeps running when stdin option is used and childProcess.stdin ends', testStreamAbortWait, noop, noopReadable(), 0, false);45test('Keeps running when stdin option is used and childProcess.stdin Duplex ends', testStreamAbortWait, noop, noopDuplex(), 0, false);46test('Keeps running when input stdio[*] option is used and input childProcess.stdio[*] ends', testStreamAbortWait, noop, noopReadable(), 3, false);47test('Keeps running when stdin option is used and childProcess.stdin ends, with a transform', testStreamAbortWait, noop, noopReadable(), 0, true);48test('Keeps running when stdin option is used and childProcess.stdin Duplex ends, with a transform', testStreamAbortWait, noop, noopDuplex(), 0, true);49test('Keeps running when input stdio[*] option is used and input childProcess.stdio[*] ends, with a transform', testStreamAbortWait, noop, noopReadable(), 3, true);44test('Keeps running when stdin option is used and subprocess.stdin ends', testStreamAbortWait, noop, noopReadable(), 0, false);45test('Keeps running when stdin option is used and subprocess.stdin Duplex ends', testStreamAbortWait, noop, noopDuplex(), 0, false);46test('Keeps running when input stdio[*] option is used and input subprocess.stdio[*] ends', testStreamAbortWait, noop, noopReadable(), 3, false);47test('Keeps running when stdin option is used and subprocess.stdin ends, with a transform', testStreamAbortWait, noop, noopReadable(), 0, true);48test('Keeps running when stdin option is used and subprocess.stdin Duplex ends, with a transform', testStreamAbortWait, noop, noopDuplex(), 0, true);49test('Keeps running when input stdio[*] option is used and input subprocess.stdio[*] ends, with a transform', testStreamAbortWait, noop, noopReadable(), 3, true);5051// eslint-disable-next-line max-params52const testStreamAbortSuccess = async (t, streamMethod, stream, fdNumber, useTransform) => {53 const childProcess = execa('noop-stdin-fd.js', [`${fdNumber}`], getStreamStdio(fdNumber, stream, useTransform));54 streamMethod({stream, childProcess, fdNumber});55 childProcess.stdin.end();53 const subprocess = execa('noop-stdin-fd.js', [`${fdNumber}`], getStreamStdio(fdNumber, stream, useTransform));54 streamMethod({stream, subprocess, fdNumber});55 subprocess.stdin.end();5657 const {stdout} = await childProcess;57 const {stdout} = await subprocess;58 t.is(stdout, '');59 t.true(stream.destroyed);60};61
2 unmodified lines
64test('Passes when input stdio[*] option aborts', testStreamAbortSuccess, destroyOptionStream, noopReadable(), 3, false);65test('Passes when stdout option ends with no more writes', testStreamAbortSuccess, endOptionStream, noopWritable(), 1, false);66test('Passes when stderr option ends with no more writes', testStreamAbortSuccess, endOptionStream, noopWritable(), 2, false);67test('Passes when output stdio[*] option ends with no more writes', testStreamAbortSuccess, endOptionStream, noopWritable(), 3, false);68test('Passes when childProcess.stdout aborts with no more writes', testStreamAbortSuccess, destroyChildStream, noopWritable(), 1, false);69test('Passes when childProcess.stdout Duplex aborts with no more writes', testStreamAbortSuccess, destroyChildStream, noopDuplex(), 1, false);70test('Passes when childProcess.stderr aborts with no more writes', testStreamAbortSuccess, destroyChildStream, noopWritable(), 2, false);71test('Passes when childProcess.stderr Duplex aborts with no more writes', testStreamAbortSuccess, destroyChildStream, noopDuplex(), 2, false);72test('Passes when output childProcess.stdio[*] aborts with no more writes', testStreamAbortSuccess, destroyChildStream, noopWritable(), 3, false);73test('Passes when output childProcess.stdio[*] Duplex aborts with no more writes', testStreamAbortSuccess, destroyChildStream, noopDuplex(), 3, false);68test('Passes when subprocess.stdout aborts with no more writes', testStreamAbortSuccess, destroySubprocessStream, noopWritable(), 1, false);69test('Passes when subprocess.stdout Duplex aborts with no more writes', testStreamAbortSuccess, destroySubprocessStream, noopDuplex(), 1, false);70test('Passes when subprocess.stderr aborts with no more writes', testStreamAbortSuccess, destroySubprocessStream, noopWritable(), 2, false);71test('Passes when subprocess.stderr Duplex aborts with no more writes', testStreamAbortSuccess, destroySubprocessStream, noopDuplex(), 2, false);72test('Passes when output subprocess.stdio[*] aborts with no more writes', testStreamAbortSuccess, destroySubprocessStream, noopWritable(), 3, false);73test('Passes when output subprocess.stdio[*] Duplex aborts with no more writes', testStreamAbortSuccess, destroySubprocessStream, noopDuplex(), 3, false);74test('Passes when stdin option aborts, with a transform', testStreamAbortSuccess, destroyOptionStream, noopReadable(), 0, true);75test('Passes when stdin option Duplex aborts, with a transform', testStreamAbortSuccess, destroyOptionStream, noopDuplex(), 0, true);76test('Passes when input stdio[*] option aborts, with a transform', testStreamAbortSuccess, destroyOptionStream, noopReadable(), 3, true);77test('Passes when stdout option ends with no more writes, with a transform', testStreamAbortSuccess, endOptionStream, noopWritable(), 1, true);78test('Passes when stderr option ends with no more writes, with a transform', testStreamAbortSuccess, endOptionStream, noopWritable(), 2, true);79test('Passes when output stdio[*] option ends with no more writes, with a transform', testStreamAbortSuccess, endOptionStream, noopWritable(), 3, true);80test('Passes when childProcess.stdout aborts with no more writes, with a transform', testStreamAbortSuccess, destroyChildStream, noopWritable(), 1, true);81test('Passes when childProcess.stdout Duplex aborts with no more writes, with a transform', testStreamAbortSuccess, destroyChildStream, noopDuplex(), 1, true);82test('Passes when childProcess.stderr aborts with no more writes, with a transform', testStreamAbortSuccess, destroyChildStream, noopWritable(), 2, true);83test('Passes when childProcess.stderr Duplex aborts with no more writes, with a transform', testStreamAbortSuccess, destroyChildStream, noopDuplex(), 2, true);84test('Passes when output childProcess.stdio[*] aborts with no more writes, with a transform', testStreamAbortSuccess, destroyChildStream, noopWritable(), 3, true);85test('Passes when output childProcess.stdio[*] Duplex aborts with no more writes, with a transform', testStreamAbortSuccess, destroyChildStream, noopDuplex(), 3, true);80test('Passes when subprocess.stdout aborts with no more writes, with a transform', testStreamAbortSuccess, destroySubprocessStream, noopWritable(), 1, true);81test('Passes when subprocess.stdout Duplex aborts with no more writes, with a transform', testStreamAbortSuccess, destroySubprocessStream, noopDuplex(), 1, true);82test('Passes when subprocess.stderr aborts with no more writes, with a transform', testStreamAbortSuccess, destroySubprocessStream, noopWritable(), 2, true);83test('Passes when subprocess.stderr Duplex aborts with no more writes, with a transform', testStreamAbortSuccess, destroySubprocessStream, noopDuplex(), 2, true);84test('Passes when output subprocess.stdio[*] aborts with no more writes, with a transform', testStreamAbortSuccess, destroySubprocessStream, noopWritable(), 3, true);85test('Passes when output subprocess.stdio[*] Duplex aborts with no more writes, with a transform', testStreamAbortSuccess, destroySubprocessStream, noopDuplex(), 3, true);8687// eslint-disable-next-line max-params88const testStreamAbortFail = async (t, streamMethod, stream, fdNumber, useTransform) => {89 const childProcess = execa('noop-stdin-fd.js', [`${fdNumber}`], getStreamStdio(fdNumber, stream, useTransform));90 streamMethod({stream, childProcess, fdNumber});89 const subprocess = execa('noop-stdin-fd.js', [`${fdNumber}`], getStreamStdio(fdNumber, stream, useTransform));90 streamMethod({stream, subprocess, fdNumber});91 if (fdNumber !== 0) {92 childProcess.stdin.end();92 subprocess.stdin.end();93 }9495 const error = await t.throwsAsync(childProcess);95 const error = await t.throwsAsync(subprocess);96 t.like(error, {...prematureClose, exitCode: 0});97 t.true(stream.destroyed);98};99100test('Throws abort error when childProcess.stdin aborts', testStreamAbortFail, destroyChildStream, noopReadable(), 0, false);101test('Throws abort error when childProcess.stdin Duplex aborts', testStreamAbortFail, destroyChildStream, noopDuplex(), 0, false);102test('Throws abort error when input childProcess.stdio[*] aborts', testStreamAbortFail, destroyChildStream, noopReadable(), 3, false);100test('Throws abort error when subprocess.stdin aborts', testStreamAbortFail, destroySubprocessStream, noopReadable(), 0, false);101test('Throws abort error when subprocess.stdin Duplex aborts', testStreamAbortFail, destroySubprocessStream, noopDuplex(), 0, false);102test('Throws abort error when input subprocess.stdio[*] aborts', testStreamAbortFail, destroySubprocessStream, noopReadable(), 3, false);103test('Throws abort error when stdout option aborts with no more writes', testStreamAbortFail, destroyOptionStream, noopWritable(), 1, false);104test('Throws abort error when stdout option Duplex aborts with no more writes', testStreamAbortFail, destroyOptionStream, noopDuplex(), 1, false);105test('Throws abort error when stderr option aborts with no more writes', testStreamAbortFail, destroyOptionStream, noopWritable(), 2, false);106test('Throws abort error when stderr option Duplex aborts with no more writes', testStreamAbortFail, destroyOptionStream, noopDuplex(), 2, false);107test('Throws abort error when output stdio[*] option aborts with no more writes', testStreamAbortFail, destroyOptionStream, noopWritable(), 3, false);108test('Throws abort error when output stdio[*] Duplex option aborts with no more writes', testStreamAbortFail, destroyOptionStream, noopDuplex(), 3, false);109test('Throws abort error when childProcess.stdin aborts, with a transform', testStreamAbortFail, destroyChildStream, noopReadable(), 0, true);110test('Throws abort error when childProcess.stdin Duplex aborts, with a transform', testStreamAbortFail, destroyChildStream, noopDuplex(), 0, true);111test('Throws abort error when input childProcess.stdio[*] aborts, with a transform', testStreamAbortFail, destroyChildStream, noopReadable(), 3, true);109test('Throws abort error when subprocess.stdin aborts, with a transform', testStreamAbortFail, destroySubprocessStream, noopReadable(), 0, true);110test('Throws abort error when subprocess.stdin Duplex aborts, with a transform', testStreamAbortFail, destroySubprocessStream, noopDuplex(), 0, true);111test('Throws abort error when input subprocess.stdio[*] aborts, with a transform', testStreamAbortFail, destroySubprocessStream, noopReadable(), 3, true);112test('Throws abort error when stdout option aborts with no more writes, with a transform', testStreamAbortFail, destroyOptionStream, noopWritable(), 1, true);113test('Throws abort error when stdout option Duplex aborts with no more writes, with a transform', testStreamAbortFail, destroyOptionStream, noopDuplex(), 1, true);114test('Throws abort error when stderr option aborts with no more writes, with a transform', testStreamAbortFail, destroyOptionStream, noopWritable(), 2, true);115test('Throws abort error when stderr option Duplex aborts with no more writes, with a transform', testStreamAbortFail, destroyOptionStream, noopDuplex(), 2, true);
1 unmodified line
117test('Throws abort error when output stdio[*] Duplex option aborts with no more writes, with a transform', testStreamAbortFail, destroyOptionStream, noopDuplex(), 3, true);118119// eslint-disable-next-line max-params120const testStreamEpipeFail = async (t, streamMethod, stream, fdNumber, useTransform) => {121 const childProcess = execa('noop-stdin-fd.js', [`${fdNumber}`], getStreamStdio(fdNumber, stream, useTransform));122 streamMethod({stream, childProcess, fdNumber});121 const subprocess = execa('noop-stdin-fd.js', [`${fdNumber}`], getStreamStdio(fdNumber, stream, useTransform));122 streamMethod({stream, subprocess, fdNumber});123 await setImmediate();124 childProcess.stdin.end(foobarString);124 subprocess.stdin.end(foobarString);125126 const {exitCode, stdio, stderr} = await t.throwsAsync(childProcess);126 const {exitCode, stdio, stderr} = await t.throwsAsync(subprocess);127 t.is(exitCode, 1);128 t.is(stdio[fdNumber], '');129 t.true(stream.destroyed);130 if (fdNumber !== 2 && !isWindows) {
9 unmodified lines
140test('Throws EPIPE when stderr option Duplex aborts with more writes', testStreamEpipeFail, destroyOptionStream, noopDuplex(), 2, false);141test('Throws EPIPE when output stdio[*] option ends with more writes', testStreamEpipeFail, endOptionStream, noopWritable(), 3, false);142test('Throws EPIPE when output stdio[*] option aborts with more writes', testStreamEpipeFail, destroyOptionStream, noopWritable(), 3, false);143test('Throws EPIPE when output stdio[*] option Duplex aborts with more writes', testStreamEpipeFail, destroyOptionStream, noopDuplex(), 3, false);144test('Throws EPIPE when childProcess.stdout aborts with more writes', testStreamEpipeFail, destroyChildStream, noopWritable(), 1, false);145test('Throws EPIPE when childProcess.stdout Duplex aborts with more writes', testStreamEpipeFail, destroyChildStream, noopDuplex(), 1, false);146test('Throws EPIPE when childProcess.stderr aborts with more writes', testStreamEpipeFail, destroyChildStream, noopWritable(), 2, false);147test('Throws EPIPE when childProcess.stderr Duplex aborts with more writes', testStreamEpipeFail, destroyChildStream, noopDuplex(), 2, false);148test('Throws EPIPE when output childProcess.stdio[*] aborts with more writes', testStreamEpipeFail, destroyChildStream, noopWritable(), 3, false);149test('Throws EPIPE when output childProcess.stdio[*] Duplex aborts with more writes', testStreamEpipeFail, destroyChildStream, noopDuplex(), 3, false);144test('Throws EPIPE when subprocess.stdout aborts with more writes', testStreamEpipeFail, destroySubprocessStream, noopWritable(), 1, false);145test('Throws EPIPE when subprocess.stdout Duplex aborts with more writes', testStreamEpipeFail, destroySubprocessStream, noopDuplex(), 1, false);146test('Throws EPIPE when subprocess.stderr aborts with more writes', testStreamEpipeFail, destroySubprocessStream, noopWritable(), 2, false);147test('Throws EPIPE when subprocess.stderr Duplex aborts with more writes', testStreamEpipeFail, destroySubprocessStream, noopDuplex(), 2, false);148test('Throws EPIPE when output subprocess.stdio[*] aborts with more writes', testStreamEpipeFail, destroySubprocessStream, noopWritable(), 3, false);149test('Throws EPIPE when output subprocess.stdio[*] Duplex aborts with more writes', testStreamEpipeFail, destroySubprocessStream, noopDuplex(), 3, false);150test('Throws EPIPE when stdout option ends with more writes, with a transform', testStreamEpipeFail, endOptionStream, noopWritable(), 1, true);151test('Throws EPIPE when stdout option aborts with more writes, with a transform', testStreamEpipeFail, destroyOptionStream, noopWritable(), 1, true);152test('Throws EPIPE when stdout option Duplex aborts with more writes, with a transform', testStreamEpipeFail, destroyOptionStream, noopDuplex(), 1, true);153test('Throws EPIPE when stderr option ends with more writes, with a transform', testStreamEpipeFail, endOptionStream, noopWritable(), 2, true);
1 unmodified line
155test('Throws EPIPE when stderr option Duplex aborts with more writes, with a transform', testStreamEpipeFail, destroyOptionStream, noopDuplex(), 2, true);156test('Throws EPIPE when output stdio[*] option ends with more writes, with a transform', testStreamEpipeFail, endOptionStream, noopWritable(), 3, true);157test('Throws EPIPE when output stdio[*] option aborts with more writes, with a transform', testStreamEpipeFail, destroyOptionStream, noopWritable(), 3, true);158test('Throws EPIPE when output stdio[*] option Duplex aborts with more writes, with a transform', testStreamEpipeFail, destroyOptionStream, noopDuplex(), 3, true);159test('Throws EPIPE when childProcess.stdout aborts with more writes, with a transform', testStreamEpipeFail, destroyChildStream, noopWritable(), 1, true);160test('Throws EPIPE when childProcess.stdout Duplex aborts with more writes, with a transform', testStreamEpipeFail, destroyChildStream, noopDuplex(), 1, true);161test('Throws EPIPE when childProcess.stderr aborts with more writes, with a transform', testStreamEpipeFail, destroyChildStream, noopWritable(), 2, true);162test('Throws EPIPE when childProcess.stderr Duplex aborts with more writes, with a transform', testStreamEpipeFail, destroyChildStream, noopDuplex(), 2, true);163test('Throws EPIPE when output childProcess.stdio[*] aborts with more writes, with a transform', testStreamEpipeFail, destroyChildStream, noopWritable(), 3, true);164test('Throws EPIPE when output childProcess.stdio[*] Duplex aborts with more writes, with a transform', testStreamEpipeFail, destroyChildStream, noopDuplex(), 3, true);159test('Throws EPIPE when subprocess.stdout aborts with more writes, with a transform', testStreamEpipeFail, destroySubprocessStream, noopWritable(), 1, true);160test('Throws EPIPE when subprocess.stdout Duplex aborts with more writes, with a transform', testStreamEpipeFail, destroySubprocessStream, noopDuplex(), 1, true);161test('Throws EPIPE when subprocess.stderr aborts with more writes, with a transform', testStreamEpipeFail, destroySubprocessStream, noopWritable(), 2, true);162test('Throws EPIPE when subprocess.stderr Duplex aborts with more writes, with a transform', testStreamEpipeFail, destroySubprocessStream, noopDuplex(), 2, true);163test('Throws EPIPE when output subprocess.stdio[*] aborts with more writes, with a transform', testStreamEpipeFail, destroySubprocessStream, noopWritable(), 3, true);164test('Throws EPIPE when output subprocess.stdio[*] Duplex aborts with more writes, with a transform', testStreamEpipeFail, destroySubprocessStream, noopDuplex(), 3, true);165166// eslint-disable-next-line max-params167const testStreamError = async (t, streamMethod, stream, fdNumber, useTransform) => {168 const childProcess = execa('empty.js', getStreamStdio(fdNumber, stream, useTransform));168 const subprocess = execa('empty.js', getStreamStdio(fdNumber, stream, useTransform));169 const error = new Error('test');170 streamMethod({stream, childProcess, fdNumber, error});170 streamMethod({stream, subprocess, fdNumber, error});171172 t.is(await t.throwsAsync(childProcess), error);172 t.is(await t.throwsAsync(subprocess), error);173 const {exitCode, signal, isTerminated, failed} = error;174 t.is(exitCode, 0);175 t.is(signal, undefined);176 t.false(isTerminated);
9 unmodified lines
186test('Throws stream error when stderr option Duplex errors', testStreamError, destroyOptionStream, noopDuplex(), 2, false);187test('Throws stream error when output stdio[*] option errors', testStreamError, destroyOptionStream, noopWritable(), 3, false);188test('Throws stream error when output stdio[*] Duplex option errors', testStreamError, destroyOptionStream, noopDuplex(), 3, false);189test('Throws stream error when input stdio[*] option errors', testStreamError, destroyOptionStream, noopReadable(), 3, false);190test('Throws stream error when childProcess.stdin errors', testStreamError, destroyChildStream, noopReadable(), 0, false);191test('Throws stream error when childProcess.stdin Duplex errors', testStreamError, destroyChildStream, noopDuplex(), 0, false);192test('Throws stream error when childProcess.stdout errors', testStreamError, destroyChildStream, noopWritable(), 1, false);193test('Throws stream error when childProcess.stdout Duplex errors', testStreamError, destroyChildStream, noopDuplex(), 1, false);194test('Throws stream error when childProcess.stderr errors', testStreamError, destroyChildStream, noopWritable(), 2, false);195test('Throws stream error when childProcess.stderr Duplex errors', testStreamError, destroyChildStream, noopDuplex(), 2, false);196test('Throws stream error when output childProcess.stdio[*] errors', testStreamError, destroyChildStream, noopWritable(), 3, false);197test('Throws stream error when output childProcess.stdio[*] Duplex errors', testStreamError, destroyChildStream, noopDuplex(), 3, false);198test('Throws stream error when input childProcess.stdio[*] errors', testStreamError, destroyChildStream, noopReadable(), 3, false);190test('Throws stream error when subprocess.stdin errors', testStreamError, destroySubprocessStream, noopReadable(), 0, false);191test('Throws stream error when subprocess.stdin Duplex errors', testStreamError, destroySubprocessStream, noopDuplex(), 0, false);192test('Throws stream error when subprocess.stdout errors', testStreamError, destroySubprocessStream, noopWritable(), 1, false);193test('Throws stream error when subprocess.stdout Duplex errors', testStreamError, destroySubprocessStream, noopDuplex(), 1, false);194test('Throws stream error when subprocess.stderr errors', testStreamError, destroySubprocessStream, noopWritable(), 2, false);195test('Throws stream error when subprocess.stderr Duplex errors', testStreamError, destroySubprocessStream, noopDuplex(), 2, false);196test('Throws stream error when output subprocess.stdio[*] errors', testStreamError, destroySubprocessStream, noopWritable(), 3, false);197test('Throws stream error when output subprocess.stdio[*] Duplex errors', testStreamError, destroySubprocessStream, noopDuplex(), 3, false);198test('Throws stream error when input subprocess.stdio[*] errors', testStreamError, destroySubprocessStream, noopReadable(), 3, false);199test('Throws stream error when stdin option errors, with a transform', testStreamError, destroyOptionStream, noopReadable(), 0, true);200test('Throws stream error when stdin option Duplex errors, with a transform', testStreamError, destroyOptionStream, noopDuplex(), 0, true);201test('Throws stream error when stdout option errors, with a transform', testStreamError, destroyOptionStream, noopWritable(), 1, true);202test('Throws stream error when stdout option Duplex errors, with a transform', testStreamError, destroyOptionStream, noopDuplex(), 1, true);
1 unmodified line
204test('Throws stream error when stderr option Duplex errors, with a transform', testStreamError, destroyOptionStream, noopDuplex(), 2, true);205test('Throws stream error when output stdio[*] option errors, with a transform', testStreamError, destroyOptionStream, noopWritable(), 3, true);206test('Throws stream error when output stdio[*] Duplex option errors, with a transform', testStreamError, destroyOptionStream, noopDuplex(), 3, true);207test('Throws stream error when input stdio[*] option errors, with a transform', testStreamError, destroyOptionStream, noopReadable(), 3, true);208test('Throws stream error when childProcess.stdin errors, with a transform', testStreamError, destroyChildStream, noopReadable(), 0, true);209test('Throws stream error when childProcess.stdin Duplex errors, with a transform', testStreamError, destroyChildStream, noopDuplex(), 0, true);210test('Throws stream error when childProcess.stdout errors, with a transform', testStreamError, destroyChildStream, noopWritable(), 1, true);211test('Throws stream error when childProcess.stdout Duplex errors, with a transform', testStreamError, destroyChildStream, noopDuplex(), 1, true);212test('Throws stream error when childProcess.stderr errors, with a transform', testStreamError, destroyChildStream, noopWritable(), 2, true);213test('Throws stream error when childProcess.stderr Duplex errors, with a transform', testStreamError, destroyChildStream, noopDuplex(), 2, true);214test('Throws stream error when output childProcess.stdio[*] errors, with a transform', testStreamError, destroyChildStream, noopWritable(), 3, true);215test('Throws stream error when output childProcess.stdio[*] Duplex errors, with a transform', testStreamError, destroyChildStream, noopDuplex(), 3, true);216test('Throws stream error when input childProcess.stdio[*] errors, with a transform', testStreamError, destroyChildStream, noopReadable(), 3, true);208test('Throws stream error when subprocess.stdin errors, with a transform', testStreamError, destroySubprocessStream, noopReadable(), 0, true);209test('Throws stream error when subprocess.stdin Duplex errors, with a transform', testStreamError, destroySubprocessStream, noopDuplex(), 0, true);210test('Throws stream error when subprocess.stdout errors, with a transform', testStreamError, destroySubprocessStream, noopWritable(), 1, true);211test('Throws stream error when subprocess.stdout Duplex errors, with a transform', testStreamError, destroySubprocessStream, noopDuplex(), 1, true);212test('Throws stream error when subprocess.stderr errors, with a transform', testStreamError, destroySubprocessStream, noopWritable(), 2, true);213test('Throws stream error when subprocess.stderr Duplex errors, with a transform', testStreamError, destroySubprocessStream, noopDuplex(), 2, true);214test('Throws stream error when output subprocess.stdio[*] errors, with a transform', testStreamError, destroySubprocessStream, noopWritable(), 3, true);215test('Throws stream error when output subprocess.stdio[*] Duplex errors, with a transform', testStreamError, destroySubprocessStream, noopDuplex(), 3, true);216test('Throws stream error when input subprocess.stdio[*] errors, with a transform', testStreamError, destroySubprocessStream, noopReadable(), 3, true);
modified:test/verbose/complete.js+10 added-10 removed
4 unmodified lines
5import {foobarString} from '../helpers/input.js';6import {7 nestedExecaAsync,8 nestedExecaSync,9 runErrorProcess,10 runWarningProcess,11 runEarlyErrorProcess,9 runErrorSubprocess,10 runWarningSubprocess,11 runEarlyErrorSubprocess,12 getCompletionLine,13 getCompletionLines,14 testTimestamp,15 getVerboseOption,
19 unmodified lines
35test('Does not print completion, verbose "none"', testNoPrintCompletion, nestedExecaAsync);36test('Does not print completion, verbose "none", sync', testNoPrintCompletion, nestedExecaSync);3738const testPrintCompletionError = async (t, execaMethod) => {39 const stderr = await runErrorProcess(t, 'short', execaMethod);39 const stderr = await runErrorSubprocess(t, 'short', execaMethod);40 t.is(getCompletionLine(stderr), `${testTimestamp} [0] × (done in 0ms)`);41};4243test('Prints completion after errors', testPrintCompletionError, nestedExecaAsync);44test('Prints completion after errors, sync', testPrintCompletionError, nestedExecaSync);4546const testPrintCompletionWarning = async (t, execaMethod) => {47 const stderr = await runWarningProcess(t, execaMethod);47 const stderr = await runWarningSubprocess(t, execaMethod);48 t.is(getCompletionLine(stderr), `${testTimestamp} [0] ‼ (done in 0ms)`);49};5051test('Prints completion after errors, "reject" false', testPrintCompletionWarning, nestedExecaAsync);52test('Prints completion after errors, "reject" false, sync', testPrintCompletionWarning, nestedExecaSync);5354const testPrintCompletionEarly = async (t, execaMethod) => {55 const stderr = await runEarlyErrorProcess(t, execaMethod);55 const stderr = await runEarlyErrorSubprocess(t, execaMethod);56 t.is(getCompletionLine(stderr), `${testTimestamp} [0] × (done in 0ms)`);57};5859test('Prints completion after early validation errors', testPrintCompletionEarly, nestedExecaAsync);
19 unmodified lines
79};8081test('Prints both durations piped with .pipe("file")', testPipeDuration, 'file', true, true);82test('Prints both durations piped with .pipe`command`', testPipeDuration, 'script', true, true);83test('Prints both durations piped with .pipe(childProcess)', testPipeDuration, 'process', true, true);83test('Prints both durations piped with .pipe(subprocess)', testPipeDuration, 'subprocesses', true, true);84test('Prints first duration piped with .pipe("file")', testPipeDuration, 'file', true, false);85test('Prints first duration piped with .pipe`command`', testPipeDuration, 'script', true, false);86test('Prints first duration piped with .pipe(childProcess)', testPipeDuration, 'process', true, false);86test('Prints first duration piped with .pipe(subprocess)', testPipeDuration, 'subprocesses', true, false);87test('Prints second duration piped with .pipe("file")', testPipeDuration, 'file', false, true);88test('Prints second duration piped with .pipe`command`', testPipeDuration, 'script', false, true);89test('Prints second duration piped with .pipe(childProcess)', testPipeDuration, 'process', false, true);89test('Prints second duration piped with .pipe(subprocess)', testPipeDuration, 'subprocesses', false, true);90test('Prints neither durations piped with .pipe("file")', testPipeDuration, 'file', false, false);91test('Prints neither durations piped with .pipe`command`', testPipeDuration, 'script', false, false);92test('Prints neither durations piped with .pipe(childProcess)', testPipeDuration, 'process', false, false);92test('Prints neither durations piped with .pipe(subprocess)', testPipeDuration, 'subprocesses', false, false);
modified:test/verbose/error.js+6 added-6 removed
6 unmodified lines
7 QUOTE,8 nestedExeca,9 nestedExecaAsync,10 nestedExecaSync,11 runEarlyErrorProcess,11 runEarlyErrorSubprocess,12 getErrorLine,13 getErrorLines,14 testTimestamp,15 getVerboseOption,
30 unmodified lines
46test('Does not print error if none', testPrintNoError, nestedExecaAsync);47test('Does not print error if none, sync', testPrintNoError, nestedExecaSync);4849const testPrintErrorEarly = async (t, execaMethod) => {50 const stderr = await runEarlyErrorProcess(t, execaMethod);50 const stderr = await runEarlyErrorSubprocess(t, execaMethod);51 t.is(getErrorLine(stderr), `${testTimestamp} [0] × TypeError: The "cwd" option must be a string or a file URL: true.`);52};5354test('Prints early validation error', testPrintErrorEarly, nestedExecaAsync);
24 unmodified lines
79};8081test('Prints both errors piped with .pipe("file")', testPipeError, 'file', true, true);82test('Prints both errors piped with .pipe`command`', testPipeError, 'script', true, true);83test('Prints both errors piped with .pipe(childProcess)', testPipeError, 'process', true, true);83test('Prints both errors piped with .pipe(subprocess)', testPipeError, 'subprocesses', true, true);84test('Prints first error piped with .pipe("file")', testPipeError, 'file', true, false);85test('Prints first error piped with .pipe`command`', testPipeError, 'script', true, false);86test('Prints first error piped with .pipe(childProcess)', testPipeError, 'process', true, false);86test('Prints first error piped with .pipe(subprocess)', testPipeError, 'subprocesses', true, false);87test('Prints second error piped with .pipe("file")', testPipeError, 'file', false, true);88test('Prints second error piped with .pipe`command`', testPipeError, 'script', false, true);89test('Prints second error piped with .pipe(childProcess)', testPipeError, 'process', false, true);89test('Prints second error piped with .pipe(subprocess)', testPipeError, 'subprocesses', false, true);90test('Prints neither errors piped with .pipe("file")', testPipeError, 'file', false, false);91test('Prints neither errors piped with .pipe`command`', testPipeError, 'script', false, false);92test('Prints neither errors piped with .pipe(childProcess)', testPipeError, 'process', false, false);92test('Prints neither errors piped with .pipe(subprocess)', testPipeError, 'subprocesses', false, false);9394test('Quotes spaces from error', async t => {95 const {stderr} = await t.throwsAsync(nestedExecaFail('noop-forever.js', ['foo bar'], {verbose: 'short'}));96 t.deepEqual(getErrorLines(stderr), [
36 unmodified lines
modified:test/verbose/output.js+22 added-22 removed
10 unmodified lines
11import {12 nestedExeca,13 nestedExecaAsync,14 nestedExecaSync,15 runErrorProcess,15 runErrorSubprocess,16 getOutputLine,17 getOutputLines,18 testTimestamp,19 getVerboseOption,
33 unmodified lines
53test('Does not print stdio[*], verbose "short", sync', testNoPrintOutput, 'short', 3, nestedExecaSync);54test('Does not print stdio[*], verbose "full", sync', testNoPrintOutput, 'full', 3, nestedExecaSync);5556test('Prints stdout after errors', async t => {57 const stderr = await runErrorProcess(t, 'full', nestedExecaAsync);57 const stderr = await runErrorSubprocess(t, 'full', nestedExecaAsync);58 t.is(getOutputLine(stderr), `${testTimestamp} [0] ${foobarString}`);59});6061const testPipeOutput = async (t, fixtureName, sourceVerbose, destinationVerbose) => {
13 unmodified lines
75};7677test('Prints stdout if both verbose with .pipe("file")', testPipeOutput, 'file', true, true);78test('Prints stdout if both verbose with .pipe`command`', testPipeOutput, 'script', true, true);79test('Prints stdout if both verbose with .pipe(childProcess)', testPipeOutput, 'process', true, true);79test('Prints stdout if both verbose with .pipe(subprocess)', testPipeOutput, 'subprocesses', true, true);80test('Prints stdout if only second verbose with .pipe("file")', testPipeOutput, 'file', false, true);81test('Prints stdout if only second verbose with .pipe`command`', testPipeOutput, 'script', false, true);82test('Prints stdout if only second verbose with .pipe(childProcess)', testPipeOutput, 'process', false, true);82test('Prints stdout if only second verbose with .pipe(subprocess)', testPipeOutput, 'subprocesses', false, true);83test('Does not print stdout if only first verbose with .pipe("file")', testPipeOutput, 'file', true, false);84test('Does not print stdout if only first verbose with .pipe`command`', testPipeOutput, 'script', true, false);85test('Does not print stdout if only first verbose with .pipe(childProcess)', testPipeOutput, 'process', true, false);85test('Does not print stdout if only first verbose with .pipe(subprocess)', testPipeOutput, 'subprocesses', true, false);86test('Does not print stdout if neither verbose with .pipe("file")', testPipeOutput, 'file', false, false);87test('Does not print stdout if neither verbose with .pipe`command`', testPipeOutput, 'script', false, false);88test('Does not print stdout if neither verbose with .pipe(childProcess)', testPipeOutput, 'process', false, false);88test('Does not print stdout if neither verbose with .pipe(subprocess)', testPipeOutput, 'subprocesses', false, false);8990test('Does not quote spaces from stdout', async t => {91 const {stderr} = await nestedExecaAsync('noop.js', ['foo bar'], {verbose: 'full'});92 t.is(getOutputLine(stderr), `${testTimestamp} [0] foo bar`);
19 unmodified lines
112 t.is(getOutputLine(stderr), `${testTimestamp} [0] \\u0001`);113});114115const testStdioSame = async (t, fdNumber) => {116 const childProcess = execa('nested-send.js', [JSON.stringify({verbose: true}), 'noop-fd.js', `${fdNumber}`, foobarString], {ipc: true});117 const [[{stdio}]] = await Promise.all([once(childProcess, 'message'), childProcess]);116 const subprocess = execa('nested-send.js', [JSON.stringify({verbose: true}), 'noop-fd.js', `${fdNumber}`, foobarString], {ipc: true});117 const [[{stdio}]] = await Promise.all([once(subprocess, 'message'), subprocess]);118 t.is(stdio[fdNumber], foobarString);119};120121test('Does not change stdout', testStdioSame, 1);
17 unmodified lines
139 t.is(lines.at(-1), `${testTimestamp} [0] ]`);140});141142test('Prints stdout one line at a time', async t => {143 const childProcess = nestedExecaAsync('noop-progressive.js', [foobarString], {verbose: 'full'});143 const subprocess = nestedExecaAsync('noop-progressive.js', [foobarString], {verbose: 'full'});144145 for await (const chunk of on(childProcess.stderr, 'data')) {145 for await (const chunk of on(subprocess.stderr, 'data')) {146 const outputLine = getOutputLine(chunk.toString().trim());147 if (outputLine !== undefined) {148 t.is(outputLine, `${testTimestamp} [0] ${foobarString}`);149 break;150 }151 }152153 await childProcess;153 await subprocess;154});155156test('Prints stdout progressively, interleaved', async t => {157 const childProcess = nestedExecaDouble('noop-repeat.js', ['1', `${foobarString}\n`], {verbose: 'full'});157 const subprocess = nestedExecaDouble('noop-repeat.js', ['1', `${foobarString}\n`], {verbose: 'full'});158159 let firstProcessPrinted = false;160 let secondProcessPrinted = false;161 for await (const chunk of on(childProcess.stderr, 'data')) {159 let firstSubprocessPrinted = false;160 let secondSubprocessPrinted = false;161 for await (const chunk of on(subprocess.stderr, 'data')) {162 const outputLine = getOutputLine(chunk.toString().trim());163 if (outputLine === undefined) {164 continue;165 }166167 if (outputLine.includes(foobarString)) {168 t.is(outputLine, `${testTimestamp} [0] ${foobarString}`);169 firstProcessPrinted ||= true;169 firstSubprocessPrinted ||= true;170 } else {171 t.is(outputLine, `${testTimestamp} [1] ${foobarString.toUpperCase()}`);172 secondProcessPrinted ||= true;172 secondSubprocessPrinted ||= true;173 }174175 if (firstProcessPrinted && secondProcessPrinted) {175 if (firstSubprocessPrinted && secondSubprocessPrinted) {176 break;177 }178 }179180 childProcess.kill();181 await t.throwsAsync(childProcess);180 subprocess.kill();181 await t.throwsAsync(subprocess);182});183184test('Prints stdout, single newline', async t => {185 const {stderr} = await nestedExecaAsync('noop-fd.js', ['1', '\n'], {verbose: 'full'});
13 unmodified lines
199test('Does not print stdout, stdout 1', testNoOutputOptions, {stdout: 1});200test('Does not print stdout, stdout Writable', testNoOutputOptions, {}, 'nested-writable.js');201test('Does not print stdout, stdout WritableStream', testNoOutputOptions, {}, 'nested-writable-web.js');202test('Does not print stdout, .pipe(stream)', testNoOutputOptions, {}, 'nested-pipe-stream.js');203test('Does not print stdout, .pipe(childProcess)', testNoOutputOptions, {}, 'nested-pipe-child-process.js');203test('Does not print stdout, .pipe(subprocess)', testNoOutputOptions, {}, 'nested-pipe-subprocess.js');204205const testStdoutFile = async (t, fixtureName, getStdout) => {206 const file = tempfile();207 const {stderr} = await nestedExeca(fixtureName, 'noop.js', [foobarString], {verbose: 'full', stdout: getStdout(file)});
22 unmodified lines
230 t.is(getOutputLine(stderr), `${testTimestamp} [0] ${foobarString}`);231};232233test('Prints stdout, .pipe(stream) + .unpipe()', testPrintOutputFixture, 'nested-pipe-stream.js', 'true');234test('Prints stdout, .pipe(childProcess) + .unpipe()', testPrintOutputFixture, 'nested-pipe-child-process.js', 'true');234test('Prints stdout, .pipe(subprocess) + .unpipe()', testPrintOutputFixture, 'nested-pipe-subprocess.js', 'true');
modified:test/verbose/start.js+9 added-9 removed
5 unmodified lines
6import {7 QUOTE,8 nestedExecaAsync,9 nestedExecaSync,10 runErrorProcess,11 runEarlyErrorProcess,10 runErrorSubprocess,11 runEarlyErrorSubprocess,12 getCommandLine,13 getCommandLines,14 testTimestamp,15 getVerboseOption,
19 unmodified lines
35test('Does not print command, verbose "none"', testNoPrintCommand, nestedExecaAsync);36test('Does not print command, verbose "none", sync', testNoPrintCommand, nestedExecaSync);3738const testPrintCommandError = async (t, execaMethod) => {39 const stderr = await runErrorProcess(t, 'short', execaMethod);39 const stderr = await runErrorSubprocess(t, 'short', execaMethod);40 t.is(getCommandLine(stderr), `${testTimestamp} [0] $ noop-fail.js 1 ${foobarString}`);41};4243test('Prints command after errors', testPrintCommandError, nestedExecaAsync);44test('Prints command after errors, sync', testPrintCommandError, nestedExecaSync);4546const testPrintCommandEarly = async (t, execaMethod) => {47 const stderr = await runEarlyErrorProcess(t, execaMethod);47 const stderr = await runEarlyErrorSubprocess(t, execaMethod);48 t.is(getCommandLine(stderr), `${testTimestamp} [0] $ noop.js ${foobarString}`);49};5051test('Prints command before early validation errors', testPrintCommandEarly, nestedExecaAsync);
6 unmodified lines
58 foobarString,59 JSON.stringify(getVerboseOption(destinationVerbose)),60 'stdin.js',61 ]);62 const pipeSymbol = fixtureName === 'process' ? '$' : '|';62 const pipeSymbol = fixtureName === 'subprocesses' ? '$' : '|';63 const lines = getCommandLines(stderr);64 t.is(lines.includes(`${testTimestamp} [0] $ noop.js ${foobarString}`), sourceVerbose);65 t.is(lines.includes(`${testTimestamp} [${sourceVerbose ? 1 : 0}] ${pipeSymbol} stdin.js`), destinationVerbose);66};6768test('Prints both commands piped with .pipe("file")', testPipeCommand, 'file', true, true);69test('Prints both commands piped with .pipe`command`', testPipeCommand, 'script', true, true);70test('Prints both commands piped with .pipe(childProcess)', testPipeCommand, 'process', true, true);70test('Prints both commands piped with .pipe(subprocess)', testPipeCommand, 'subprocesses', true, true);71test('Prints first command piped with .pipe("file")', testPipeCommand, 'file', true, false);72test('Prints first command piped with .pipe`command`', testPipeCommand, 'script', true, false);73test('Prints first command piped with .pipe(childProcess)', testPipeCommand, 'process', true, false);73test('Prints first command piped with .pipe(subprocess)', testPipeCommand, 'subprocesses', true, false);74test('Prints second command piped with .pipe("file")', testPipeCommand, 'file', false, true);75test('Prints second command piped with .pipe`command`', testPipeCommand, 'script', false, true);76test('Prints second command piped with .pipe(childProcess)', testPipeCommand, 'process', false, true);76test('Prints second command piped with .pipe(subprocess)', testPipeCommand, 'subprocesses', false, true);77test('Prints neither commands piped with .pipe("file")', testPipeCommand, 'file', false, false);78test('Prints neither commands piped with .pipe`command`', testPipeCommand, 'script', false, false);79test('Prints neither commands piped with .pipe(childProcess)', testPipeCommand, 'process', false, false);79test('Prints neither commands piped with .pipe(subprocess)', testPipeCommand, 'subprocesses', false, false);8081test('Quotes spaces from command', async t => {82 const {stderr} = await nestedExecaAsync('noop.js', ['foo bar'], {verbose: 'short'});83 t.is(getCommandLine(stderr), `${testTimestamp} [0] $ noop.js ${QUOTE}foo bar${QUOTE}`);
21 unmodified lines
modified:test/promise.js+2 added-2 removed
47 unmodified lines
48 const {stdout} = await execa('no-await.js', [JSON.stringify(options), fixtureName]);49 t.true(stdout.includes(message));50};5152test('Throws if promise is not awaited and process fails', testNoAwait, 'fail.js', {}, 'exit code 2');53test('Throws if promise is not awaited and process times out', testNoAwait, 'forever.js', {timeout: 1}, 'timed out');52test('Throws if promise is not awaited and subprocess fails', testNoAwait, 'fail.js', {}, 'exit code 2');53test('Throws if promise is not awaited and subprocess times out', testNoAwait, 'forever.js', {timeout: 1}, 'timed out');
modified:test/script.js+14 added-14 removed
10 unmodified lines
11 templates.raw = [string];12 return $(templates);13};1415const testScriptStdout = async (t, getChildProcess, expectedStdout) => {16 const {stdout} = await getChildProcess();15const testScriptStdout = async (t, getSubprocess, expectedStdout) => {16 const {stdout} = await getSubprocess();17 t.is(stdout, expectedStdout);18};1920test('$ executes command', testScriptStdout, () => $`echo.js foo bar`, 'foo\nbar');
216 unmodified lines
237test('$ splits expressions - \\u{0063}}', testScriptStdout, () => $`echo.js ${'a'}\u{0063}}${'b'}`, 'ac}b');238test('$ concatenates tokens - \\u{0063}}', testScriptStdout, () => $`echo.js \u{0063}}a\u{0063}} b`, 'c}ac}\nb');239test('$ concatenates expressions - \\u{0063}}', testScriptStdout, () => $`echo.js \u{0063}}${'a'}\u{0063}} b`, 'c}ac}\nb');240241const testScriptErrorStdout = async (t, getChildProcess) => {242 t.throws(getChildProcess, {message: /null bytes/});241const testScriptErrorStdout = async (t, getSubprocess) => {242 t.throws(getSubprocess, {message: /null bytes/});243};244245test('$ handles tokens - \\0', testScriptErrorStdout, () => $`echo.js \0`);246test('$ splits tokens - \\0', testScriptErrorStdout, () => $`echo.js a\0b`);247test('$ splits expressions - \\0', testScriptErrorStdout, () => $`echo.js ${'a'}\0${'b'}`);248test('$ concatenates tokens - \\0', testScriptErrorStdout, () => $`echo.js \0a\0 b`);249test('$ concatenates expressions - \\0', testScriptErrorStdout, () => $`echo.js \0${'a'}\0 b`);250251const testScriptStdoutSync = (t, getChildProcess, expectedStdout) => {252 const {stdout} = getChildProcess();251const testScriptStdoutSync = (t, getSubprocess, expectedStdout) => {252 const {stdout} = getSubprocess();253 t.is(stdout, expectedStdout);254};255256test('$.sync', testScriptStdoutSync, () => $.sync`echo.js foo bar`, 'foo\nbar');257test('$.sync can be called $.s', testScriptStdoutSync, () => $.s`echo.js foo bar`, 'foo\nbar');258test('$.sync accepts options', testScriptStdoutSync, () => $({stripFinalNewline: true}).sync`noop.js foo`, 'foo');259260const testReturnInterpolate = async (t, getChildProcess, expectedStdout, options = {}) => {260const testReturnInterpolate = async (t, getSubprocess, expectedStdout, options = {}) => {261 const foo = await $(options)`echo.js foo`;262 const {stdout} = await getChildProcess(foo);262 const {stdout} = await getSubprocess(foo);263 t.is(stdout, expectedStdout);264};265266test('$ allows execa return value interpolation', testReturnInterpolate, foo => $`echo.js ${foo} bar`, 'foo\nbar');267test('$ allows execa return value buffer interpolation', testReturnInterpolate, foo => $`echo.js ${foo} bar`, 'foo\nbar', {encoding: 'buffer'});268test('$ allows execa return value array interpolation', testReturnInterpolate, foo => $`echo.js ${[foo, 'bar']}`, 'foo\nbar');269test('$ allows execa return value buffer array interpolation', testReturnInterpolate, foo => $`echo.js ${[foo, 'bar']}`, 'foo\nbar', {encoding: 'buffer'});270271const testReturnInterpolateSync = (t, getChildProcess, expectedStdout, options = {}) => {271const testReturnInterpolateSync = (t, getSubprocess, expectedStdout, options = {}) => {272 const foo = $(options).sync`echo.js foo`;273 const {stdout} = getChildProcess(foo);273 const {stdout} = getSubprocess(foo);274 t.is(stdout, expectedStdout);275};276277test('$.sync allows execa return value interpolation', testReturnInterpolateSync, foo => $.sync`echo.js ${foo} bar`, 'foo\nbar');278test('$.sync allows execa return value buffer interpolation', testReturnInterpolateSync, foo => $.sync`echo.js ${foo} bar`, 'foo\nbar', {encoding: 'buffer'});279test('$.sync allows execa return value array interpolation', testReturnInterpolateSync, foo => $.sync`echo.js ${[foo, 'bar']}`, 'foo\nbar');280test('$.sync allows execa return value buffer array interpolation', testReturnInterpolateSync, foo => $.sync`echo.js ${[foo, 'bar']}`, 'foo\nbar', {encoding: 'buffer'});281282const testInvalidSequence = (t, getChildProcess) => {283 t.throws(getChildProcess, {message: /Invalid backslash sequence/});282const testInvalidSequence = (t, getSubprocess) => {283 t.throws(getSubprocess, {message: /Invalid backslash sequence/});284};285286test('$ handles invalid escape sequence - \\1', testInvalidSequence, () => $`echo.js \1`);287test('$ handles invalid escape sequence - \\u', testInvalidSequence, () => $`echo.js \u`);
9 unmodified lines
297test('$ handles invalid escape sequence - \\x0', testInvalidSequence, () => $`echo.js \x0`);298test('$ handles invalid escape sequence - \\xgg', testInvalidSequence, () => $`echo.js \xgg`);299/* eslint-enable unicorn/no-hex-escape */300301const testEmptyScript = (t, getChildProcess) => {302 t.throws(getChildProcess, {message: /Template script must not be empty/});301const testEmptyScript = (t, getSubprocess) => {302 t.throws(getSubprocess, {message: /Template script must not be empty/});303};304305test('$``', testEmptyScript, () => $``);306test('$` `', testEmptyScript, () => $` `);
61 unmodified lines
modified:index.d.ts+129 added-129 removed
311 unmodified lines
312 */313 readonly nodeOptions?: string[];314315 /**316 Write some input to the child process' `stdin`.316 Write some input to the subprocess' `stdin`.317318 See also the `inputFile` and `stdin` options.319 */320 readonly input?: string | Uint8Array | Readable;321322 /**323 Use a file as input to the child process' `stdin`.323 Use a file as input to the subprocess' `stdin`.324325 See also the `input` and `stdin` options.326 */327 readonly inputFile?: string | URL;328329 /**330 [How to setup](https://nodejs.org/api/child_process.html#child_process_options_stdio) the child process' standard input. This can be:331 - `'pipe'`: Sets [`childProcess.stdin`](https://nodejs.org/api/child_process.html#subprocessstdin) stream.330 [How to setup](https://nodejs.org/api/child_process.html#child_process_options_stdio) the subprocess' standard input. This can be:331 - `'pipe'`: Sets [`subprocess.stdin`](https://nodejs.org/api/child_process.html#subprocessstdin) stream.332 - `'overlapped'`: Like `'pipe'` but asynchronous on Windows.333 - `'ignore'`: Do not use `stdin`.334 - `'inherit'`: Re-use the current process' `stdin`.335 - an integer: Re-use a specific file descriptor from the current process.
12 unmodified lines
348 */349 readonly stdin?: StdinOption<IsSync>;350351 /**352 [How to setup](https://nodejs.org/api/child_process.html#child_process_options_stdio) the child process' standard output. This can be:353 - `'pipe'`: Sets `childProcessResult.stdout` (as a string or `Uint8Array`) and [`childProcess.stdout`](https://nodejs.org/api/child_process.html#subprocessstdout) (as a stream).352 [How to setup](https://nodejs.org/api/child_process.html#child_process_options_stdio) the subprocess' standard output. This can be:353 - `'pipe'`: Sets `subprocessResult.stdout` (as a string or `Uint8Array`) and [`subprocess.stdout`](https://nodejs.org/api/child_process.html#subprocessstdout) (as a stream).354 - `'overlapped'`: Like `'pipe'` but asynchronous on Windows.355 - `'ignore'`: Do not use `stdout`.356 - `'inherit'`: Re-use the current process' `stdout`.357 - an integer: Re-use a specific file descriptor from the current process.
10 unmodified lines
368 */369 readonly stdout?: StdoutStderrOption<IsSync>;370371 /**372 [How to setup](https://nodejs.org/api/child_process.html#child_process_options_stdio) the child process' standard error. This can be:373 - `'pipe'`: Sets `childProcessResult.stderr` (as a string or `Uint8Array`) and [`childProcess.stderr`](https://nodejs.org/api/child_process.html#subprocessstderr) (as a stream).372 [How to setup](https://nodejs.org/api/child_process.html#child_process_options_stdio) the subprocess' standard error. This can be:373 - `'pipe'`: Sets `subprocessResult.stderr` (as a string or `Uint8Array`) and [`subprocess.stderr`](https://nodejs.org/api/child_process.html#subprocessstderr) (as a stream).374 - `'overlapped'`: Like `'pipe'` but asynchronous on Windows.375 - `'ignore'`: Do not use `stderr`.376 - `'inherit'`: Re-use the current process' `stderr`.377 - an integer: Re-use a specific file descriptor from the current process.
23 unmodified lines
401402 /**403 Split `stdout` and `stderr` into lines.404 - `result.stdout`, `result.stderr`, `result.all` and `result.stdio` are arrays of lines.405 - `childProcess.stdout`, `childProcess.stderr`, `childProcess.all` and `childProcess.stdio` iterate over lines instead of arbitrary chunks.405 - `subprocess.stdout`, `subprocess.stderr`, `subprocess.all` and `subprocess.stdio` iterate over lines instead of arbitrary chunks.406 - Any stream passed to the `stdout`, `stderr` or `stdio` option receives lines instead of arbitrary chunks.407408 @default false409 */
13 unmodified lines
423 */424 readonly stripFinalNewline?: boolean;425426 /**427 If `true`, the child process uses both the `env` option and the current process' environment variables ([`process.env`](https://nodejs.org/api/process.html#processenv)).427 If `true`, the subprocess uses both the `env` option and the current process' environment variables ([`process.env`](https://nodejs.org/api/process.html#processenv)).428 If `false`, only the `env` option is used, not `process.env`.429430 @default true431 */432 readonly extendEnv?: boolean;433434 /**435 Current working directory of the child process.435 Current working directory of the subprocess.436437 This is also used to resolve the `nodePath` option when it is a relative path.438439 @default process.cwd()
2 unmodified lines
442443 /**444 Environment key-value pairs.445446 Unless the `extendEnv` option is `false`, the child process also uses the current process' environment variables ([`process.env`](https://nodejs.org/api/process.html#processenv)).446 Unless the `extendEnv` option is `false`, the subprocess also uses the current process' environment variables ([`process.env`](https://nodejs.org/api/process.html#processenv)).447448 @default process.env449 */450 readonly env?: NodeJS.ProcessEnv;451452 /**453 Explicitly set the value of `argv[0]` sent to the child process. This will be set to `command` or `file` if not specified.453 Explicitly set the value of `argv[0]` sent to the subprocess. This will be set to `command` or `file` if not specified.454 */455 readonly argv0?: string;456457 /**458 Sets the user identity of the process.458 Sets the user identity of the subprocess.459 */460 readonly uid?: number;461462 /**463 Sets the group identity of the process.463 Sets the group identity of the subprocess.464 */465 readonly gid?: number;466467 /**
15 unmodified lines
483 */484 readonly encoding?: EncodingOption;485486 /**487 If `timeout` is greater than `0`, the child process will be [terminated](#killsignal) if it runs for longer than that amount of milliseconds.487 If `timeout` is greater than `0`, the subprocess will be [terminated](#killsignal) if it runs for longer than that amount of milliseconds.488489 @default 0490 */491 readonly timeout?: number;
5 unmodified lines
497 */498 readonly maxBuffer?: number;499500 /**501 Signal used to terminate the child process when:501 Signal used to terminate the subprocess when:502 - using the `cancelSignal`, `timeout`, `maxBuffer` or `cleanup` option503 - calling [`subprocess.kill()`](https://nodejs.org/api/child_process.html#subprocesskillsignal) with no arguments504505 This can be either a name (like `"SIGTERM"`) or a number (like `9`).
2 unmodified lines
508 */509 readonly killSignal?: string | number;510511 /**512 If the child process is terminated but does not exit, forcefully exit it by sending [`SIGKILL`](https://en.wikipedia.org/wiki/Signal_(IPC)#SIGKILL).512 If the subprocess is terminated but does not exit, forcefully exit it by sending [`SIGKILL`](https://en.wikipedia.org/wiki/Signal_(IPC)#SIGKILL).513514 The grace period is 5 seconds by default. This feature can be disabled with `false`.515516 This works when the child process is terminated by either:516 This works when the subprocess is terminated by either:517 - the `cancelSignal`, `timeout`, `maxBuffer` or `cleanup` option518 - calling [`subprocess.kill()`](https://nodejs.org/api/child_process.html#subprocesskillsignal) with no arguments519520 This does not work when the child process is terminated by either:520 This does not work when the subprocess is terminated by either:521 - calling [`subprocess.kill()`](https://nodejs.org/api/child_process.html#subprocesskillsignal) with an argument522 - calling [`process.kill(subprocess.pid)`](https://nodejs.org/api/process.html#processkillpid-signal)523 - sending a termination signal from another process524525 Also, this does not work on Windows, because Windows [doesn't support signals](https://nodejs.org/api/process.html#process_signal_events): `SIGKILL` and `SIGTERM` both terminate the process immediately. Other packages (such as [`taskkill`](https://github.com/sindresorhus/taskkill)) can be used to achieve fail-safe termination on Windows.525 Also, this does not work on Windows, because Windows [doesn't support signals](https://nodejs.org/api/process.html#process_signal_events): `SIGKILL` and `SIGTERM` both terminate the subprocess immediately. Other packages (such as [`taskkill`](https://github.com/sindresorhus/taskkill)) can be used to achieve fail-safe termination on Windows.526527 @default 5000528 */529 forceKillAfterDelay?: number | false;
16 unmodified lines
546 If `verbose` is `'short'` or `'full'`, prints each command on `stderr` before executing it. When the command completes, prints its duration and (if it failed) its error.547548 If `verbose` is `'full'`, the command's `stdout` and `stderr` are printed too, unless either:549 - the `stdout`/`stderr` option is `ignore` or `inherit`.550 - the `stdout`/`stderr` is redirected to [a stream](https://nodejs.org/api/stream.html#readablepipedestination-options), a file, a file descriptor, or another child process.550 - the `stdout`/`stderr` is redirected to [a stream](https://nodejs.org/api/stream.html#readablepipedestination-options), a file, a file descriptor, or another subprocess.551 - the `encoding` option is set.552553 This can also be set to `'full'` by setting the `NODE_DEBUG=execa` environment variable in the current process.554
1 unmodified line
556 */557 readonly verbose?: 'none' | 'short' | 'full';558559 /**560 Kill the spawned process when the parent process exits unless either:561 - the spawned process is [`detached`](https://nodejs.org/api/child_process.html#child_process_options_detached)562 - the parent process is terminated abruptly, for example, with `SIGKILL` as opposed to `SIGTERM` or a normal exit560 Kill the subprocess when the current process exits unless either:561 - the subprocess is [`detached`](https://nodejs.org/api/child_process.html#child_process_options_detached)562 - the current process is terminated abruptly, for example, with `SIGKILL` as opposed to `SIGTERM` or a normal exit563564 @default true565 */566 readonly cleanup?: IfAsync<IsSync, boolean>;567568 /**569 Whether to return the child process' output using the `result.stdout`, `result.stderr`, `result.all` and `result.stdio` properties.569 Whether to return the subprocess' output using the `result.stdout`, `result.stderr`, `result.all` and `result.stdio` properties.570571 On failure, the `error.stdout`, `error.stderr`, `error.all` and `error.stdio` properties are used instead.572573 When `buffer` is `false`, the output can still be read using the `childProcess.stdout`, `childProcess.stderr`, `childProcess.stdio` and `childProcess.all` streams. If the output is read, this should be done right away to avoid missing any data.573 When `buffer` is `false`, the output can still be read using the `subprocess.stdout`, `subprocess.stderr`, `subprocess.stdio` and `subprocess.all` streams. If the output is read, this should be done right away to avoid missing any data.574575 @default true576 */577 readonly buffer?: IfAsync<IsSync, boolean>;578579 /**580 Add an `.all` property on the promise and the resolved value. The property contains the output of the process with `stdout` and `stderr` interleaved.580 Add an `.all` property on the promise and the resolved value. The property contains the output of the subprocess with `stdout` and `stderr` interleaved.581582 @default false583 */584 readonly all?: IfAsync<IsSync, boolean>;585586 /**587 Enables exchanging messages with the child process using [`childProcess.send(value)`](https://nodejs.org/api/child_process.html#subprocesssendmessage-sendhandle-options-callback) and [`childProcess.on('message', (value) => {})`](https://nodejs.org/api/child_process.html#event-message).587 Enables exchanging messages with the subprocess using [`subprocess.send(value)`](https://nodejs.org/api/child_process.html#subprocesssendmessage-sendhandle-options-callback) and [`subprocess.on('message', (value) => {})`](https://nodejs.org/api/child_process.html#event-message).588589 @default `true` if the `node` option is enabled, `false` otherwise590 */591 readonly ipc?: IfAsync<IsSync, boolean>;592593 /**594 Specify the kind of serialization used for sending messages between processes when using the `ipc` option:594 Specify the kind of serialization used for sending messages between subprocesses when using the `ipc` option:595 - `json`: Uses `JSON.stringify()` and `JSON.parse()`.596 - `advanced`: Uses [`v8.serialize()`](https://nodejs.org/api/v8.html#v8_v8_serialize_value)597598 [More info.](https://nodejs.org/api/child_process.html#child_process_advanced_serialization)
2 unmodified lines
601 */602 readonly serialization?: IfAsync<IsSync, 'json' | 'advanced'>;603604 /**605 Prepare child to run independently of its parent process. Specific behavior [depends on the platform](https://nodejs.org/api/child_process.html#child_process_options_detached).605 Prepare subprocess to run independently of the current process. Specific behavior [depends on the platform](https://nodejs.org/api/child_process.html#child_process_options_detached).606607 @default false608 */609 readonly detached?: IfAsync<IsSync, boolean>;610611 /**612 You can abort the spawned process using [`AbortController`](https://developer.mozilla.org/en-US/docs/Web/API/AbortController).612 You can abort the subprocess using [`AbortController`](https://developer.mozilla.org/en-US/docs/Web/API/AbortController).613614 When `AbortController.abort()` is called, [`.isCanceled`](https://github.com/sindresorhus/execa#iscanceled) becomes `true`.615616 @example
21 unmodified lines
638export type Options = CommonOptions<false>;639export type SyncOptions = CommonOptions<true>;640641/**642Result of a child process execution. On success this is a plain object. On failure this is also an `Error` instance.642Result of a subprocess execution. On success this is a plain object. On failure this is also an `Error` instance.643644The child process fails when:644The subprocess fails when:645- its exit code is not `0`646- it was terminated with a signal647- timing out648- being canceled649- there's not enough memory or there are already too many child processes649- there's not enough memory or there are already too many subprocesses650*/651type ExecaCommonReturnValue<IsSync extends boolean = boolean, OptionsType extends CommonOptions = CommonOptions> = {651type ExecaCommonResult<IsSync extends boolean = boolean, OptionsType extends CommonOptions = CommonOptions> = {652 /**653 The file and arguments that were run, for logging purposes.654655 This is not escaped and should not be executed directly as a process, including using `execa()` or `execaCommand()`.655 This is not escaped and should not be executed directly as a subprocess, including using `execa()` or `execaCommand()`.656 */657 command: string;658659 /**
1 unmodified line
661662 Unlike `command`, control characters are escaped, which makes it safe to print in a terminal.663664 This can also be copied and pasted into a shell, for debugging purposes.665 Since the escaping is fairly basic, this should not be executed directly as a process, including using `execa()` or `execaCommand()`.665 Since the escaping is fairly basic, this should not be executed directly as a subprocess, including using `execa()` or `execaCommand()`.666 */667 escapedCommand: string;668669 /**670 The numeric exit code of the process that was run.670 The numeric exit code of the subprocess that was run.671672 This is `undefined` when the process could not be spawned or was terminated by a [signal](#signal).672 This is `undefined` when the subprocess could not be spawned or was terminated by a [signal](#signal).673 */674 exitCode?: number;675676 /**677 The output of the process on `stdout`.677 The output of the subprocess on `stdout`.678679 This is `undefined` if the `stdout` option is set to only [`'inherit'`, `'ignore'`, `Stream` or `integer`](https://nodejs.org/api/child_process.html#child_process_options_stdio). This is an array if the `lines` option is `true`, or if the `stdout` option is a transform in object mode.680 */681 stdout: StdioOutput<'1', OptionsType>;682683 /**684 The output of the process on `stderr`.684 The output of the subprocess on `stderr`.685686 This is `undefined` if the `stderr` option is set to only [`'inherit'`, `'ignore'`, `Stream` or `integer`](https://nodejs.org/api/child_process.html#child_process_options_stdio). This is an array if the `lines` option is `true`, or if the `stderr` option is a transform in object mode.687 */688 stderr: StdioOutput<'2', OptionsType>;689690 /**691 The output of the process on `stdin`, `stdout`, `stderr` and other file descriptors.691 The output of the subprocess on `stdin`, `stdout`, `stderr` and other file descriptors.692693 Items are `undefined` when their corresponding `stdio` option is set to only [`'inherit'`, `'ignore'`, `Stream` or `integer`](https://nodejs.org/api/child_process.html#child_process_options_stdio). Items are arrays when their corresponding `stdio` option is a transform in object mode.694 */695 stdio: StdioArrayOutput<OptionsType>;696697 /**698 Whether the process failed to run.698 Whether the subprocess failed to run.699 */700 failed: boolean;701702 /**703 Whether the process timed out.703 Whether the subprocess timed out.704 */705 timedOut: boolean;706707 /**708 Whether the process was terminated by a signal (like `SIGTERM`) sent by either:708 Whether the subprocess was terminated by a signal (like `SIGTERM`) sent by either:709 - The current process.710 - Another process. This case is [not supported on Windows](https://nodejs.org/api/process.html#signal-events).711 */712 isTerminated: boolean;713714 /**715 The name of the signal (like `SIGTERM`) that terminated the process, sent by either:715 The name of the signal (like `SIGTERM`) that terminated the subprocess, sent by either:716 - The current process.717 - Another process. This case is [not supported on Windows](https://nodejs.org/api/process.html#signal-events).718719 If a signal terminated the process, this property is defined and included in the error message. Otherwise it is `undefined`.719 If a signal terminated the subprocess, this property is defined and included in the error message. Otherwise it is `undefined`.720 */721 signal?: string;722723 /**724 A human-friendly description of the signal that was used to terminate the process. For example, `Floating point arithmetic error`.724 A human-friendly description of the signal that was used to terminate the subprocess. For example, `Floating point arithmetic error`.725726 If a signal terminated the process, this property is defined and included in the error message. Otherwise it is `undefined`. It is also `undefined` when the signal is very uncommon which should seldomly happen.726 If a signal terminated the subprocess, this property is defined and included in the error message. Otherwise it is `undefined`. It is also `undefined` when the signal is very uncommon which should seldomly happen.727 */728 signalDescription?: string;729730 /**
1 unmodified line
732 */733 cwd: string;734735 /**736 Duration of the child process, in milliseconds.736 Duration of the subprocess, in milliseconds.737 */738 durationMs: number;739740 /**741 Whether the process was canceled using the `cancelSignal` option.741 Whether the subprocess was canceled using the `cancelSignal` option.742 */743 isCanceled: boolean;744745 /**746 The output of the process with `stdout` and `stderr` interleaved.746 The output of the subprocess with `stdout` and `stderr` interleaved.747748 This is `undefined` if either:749 - the `all` option is `false` (default value)750 - both `stdout` and `stderr` options are set to [`'inherit'`, `'ignore'`, `Stream` or `integer`](https://nodejs.org/api/child_process.html#child_process_options_stdio)
2 unmodified lines
753 */754 all: IfAsync<IsSync, AllOutput<OptionsType>>;755756 /**757 Results of the other processes that were piped into this child process. This is useful to inspect a series of child processes piped with each other.757 Results of the other subprocesses that were piped into this subprocess. This is useful to inspect a series of subprocesses piped with each other.758759 This array is initially empty and is populated each time the `.pipe()` method resolves.760 */761 pipedFrom: IfAsync<IsSync, ExecaReturnValue[], []>;761 pipedFrom: IfAsync<IsSync, ExecaResult[], []>;762 // Workaround for a TypeScript bug: https://github.com/microsoft/TypeScript/issues/57062763} & {};764765export type ExecaReturnValue<OptionsType extends Options = Options> = ExecaCommonReturnValue<false, OptionsType> & ErrorUnlessReject<OptionsType['reject']>;766export type ExecaSyncReturnValue<OptionsType extends SyncOptions = SyncOptions> = ExecaCommonReturnValue<true, OptionsType> & ErrorUnlessReject<OptionsType['reject']>;765export type ExecaResult<OptionsType extends Options = Options> = ExecaCommonResult<false, OptionsType> & ErrorUnlessReject<OptionsType['reject']>;766export type ExecaSyncResult<OptionsType extends SyncOptions = SyncOptions> = ExecaCommonResult<true, OptionsType> & ErrorUnlessReject<OptionsType['reject']>;767768type ErrorUnlessReject<RejectOption extends CommonOptions['reject']> = RejectOption extends false769 ? Partial<ExecaCommonError>770 : {};771772type ExecaCommonError = {773 /**774 Error message when the child process failed to run. In addition to the underlying error message, it also contains some information related to why the child process errored.774 Error message when the subprocess failed to run. In addition to the underlying error message, it also contains some information related to why the subprocess errored.775776 The child process `stderr`, `stdout` and other file descriptors' output are appended to the end, separated with newlines and not interleaved.776 The subprocess `stderr`, `stdout` and other file descriptors' output are appended to the end, separated with newlines and not interleaved.777 */778 message: string;779780 /**781 This is the same as the `message` property except it does not include the child process `stdout`/`stderr`/`stdio`.781 This is the same as the `message` property except it does not include the subprocess `stdout`/`stderr`/`stdio`.782 */783 shortMessage: string;784785 /**786 Original error message. This is the same as the `message` property excluding the child process `stdout`/`stderr`/`stdio` and some additional information added by Execa.786 Original error message. This is the same as the `message` property excluding the subprocess `stdout`/`stderr`/`stdio` and some additional information added by Execa.787788 This is `undefined` unless the child process exited due to an `error` event or a timeout.788 This is `undefined` unless the subprocess exited due to an `error` event or a timeout.789 */790 originalMessage?: string;791} & Error;792793export type ExecaError<OptionsType extends Options = Options> = ExecaCommonReturnValue<false, OptionsType> & ExecaCommonError;794export type ExecaSyncError<OptionsType extends SyncOptions = SyncOptions> = ExecaCommonReturnValue<true, OptionsType> & ExecaCommonError;793export type ExecaError<OptionsType extends Options = Options> = ExecaCommonResult<false, OptionsType> & ExecaCommonError;794export type ExecaSyncError<OptionsType extends SyncOptions = SyncOptions> = ExecaCommonResult<true, OptionsType> & ExecaCommonError;795796type StreamUnlessIgnored<797 FdNumber extends string,798 OptionsType extends Options = Options,799> = ChildProcessStream<FdNumber, IgnoresStreamResult<FdNumber, OptionsType>, OptionsType>;799> = SubprocessStream<FdNumber, IgnoresStreamResult<FdNumber, OptionsType>, OptionsType>;800801type ChildProcessStream<801type SubprocessStream<802 FdNumber extends string,803 StreamResultIgnored extends boolean,804 OptionsType extends Options = Options,805> = StreamResultIgnored extends true
32 unmodified lines
838 */839 readonly from?: 'stdout' | 'stderr' | 'all' | number;840841 /**842 Unpipe the child process when the signal aborts.842 Unpipe the subprocess when the signal aborts.843844 The `.pipe()` method will be rejected with a cancellation error.845 */846 readonly unpipeSignal?: AbortSignal;847};848849type PipableProcess = {849type PipableSubprocess = {850 /**851 [Pipe](https://nodejs.org/api/stream.html#readablepipedestination-options) the child process' `stdout` to a second Execa child process' `stdin`. This resolves with that second process' result. If either process is rejected, this is rejected with that process' error instead.851 [Pipe](https://nodejs.org/api/stream.html#readablepipedestination-options) the subprocess' `stdout` to a second Execa subprocess' `stdin`. This resolves with that second subprocess' result. If either subprocess is rejected, this is rejected with that subprocess' error instead.852853 This follows the same syntax as `execa(file, arguments?, options?)` except both regular options and pipe-specific options can be specified.854855 This can be called multiple times to chain a series of processes.855 This can be called multiple times to chain a series of subprocesses.856857 Multiple child processes can be piped to the same process. Conversely, the same child process can be piped to multiple other processes.857 Multiple subprocesses can be piped to the same subprocess. Conversely, the same subprocess can be piped to multiple other subprocesses.858859 This is usually the preferred method to pipe processes.859 This is usually the preferred method to pipe subprocesses.860 */861 pipe<OptionsType extends Options & PipeOptions = {}>(862 file: string | URL,863 arguments?: readonly string[],864 options?: OptionsType,865 ): Promise<ExecaReturnValue<OptionsType>> & PipableProcess;865 ): Promise<ExecaResult<OptionsType>> & PipableSubprocess;866 pipe<OptionsType extends Options & PipeOptions = {}>(867 file: string | URL,868 options?: OptionsType,869 ): Promise<ExecaReturnValue<OptionsType>> & PipableProcess;869 ): Promise<ExecaResult<OptionsType>> & PipableSubprocess;870871 /**872 Like `.pipe(file, arguments?, options?)` but using a `command` template string instead. This follows the same syntax as `$`.873874 This is the preferred method to pipe processes when using `$`.874 This is the preferred method to pipe subprocesses when using `$`.875 */876 pipe(templates: TemplateStringsArray, ...expressions: readonly TemplateExpression[]):877 Promise<ExecaReturnValue<{}>> & PipableProcess;877 Promise<ExecaResult<{}>> & PipableSubprocess;878 pipe<OptionsType extends Options & PipeOptions = {}>(options: OptionsType):879 (templates: TemplateStringsArray, ...expressions: readonly TemplateExpression[])880 => Promise<ExecaReturnValue<OptionsType>> & PipableProcess;880 => Promise<ExecaResult<OptionsType>> & PipableSubprocess;881882 /**883 Like `.pipe(file, arguments?, options?)` but using the return value of another `execa()` call instead.884885 This is the most advanced method to pipe processes. It is useful in specific cases, such as piping multiple child processes to the same process.885 This is the most advanced method to pipe subprocesses. It is useful in specific cases, such as piping multiple subprocesses to the same subprocess.886 */887 pipe<Destination extends ExecaChildProcess>(destination: Destination, options?: PipeOptions):888 Promise<Awaited<Destination>> & PipableProcess;887 pipe<Destination extends ExecaSubprocess>(destination: Destination, options?: PipeOptions):888 Promise<Awaited<Destination>> & PipableSubprocess;889};890891export type ExecaChildPromise<OptionsType extends Options = Options> = {891export type ExecaResultPromise<OptionsType extends Options = Options> = {892 stdin: StreamUnlessIgnored<'0', OptionsType>;893894 stdout: StreamUnlessIgnored<'1', OptionsType>;895
9 unmodified lines
905 all: AllStream<OptionsType>;906907 catch<ResultType = never>(908 onRejected?: (reason: ExecaError<OptionsType>) => ResultType | PromiseLike<ResultType>909 ): Promise<ExecaReturnValue<OptionsType> | ResultType>;909 ): Promise<ExecaResult<OptionsType> | ResultType>;910911 /**912 Sends a [signal](https://nodejs.org/api/os.html#signal-constants) to the child process. The default signal is the `killSignal` option. `killSignal` defaults to `SIGTERM`, which terminates the child process.912 Sends a [signal](https://nodejs.org/api/os.html#signal-constants) to the subprocess. The default signal is the `killSignal` option. `killSignal` defaults to `SIGTERM`, which terminates the subprocess.913914 This returns `false` when the signal could not be sent, for example when the child process has already exited.914 This returns `false` when the signal could not be sent, for example when the subprocess has already exited.915916 When an error is passed as argument, its message and stack trace are kept in the child process' error. The child process is then terminated with the default signal. This does not emit the [`error` event](https://nodejs.org/api/child_process.html#event-error).916 When an error is passed as argument, its message and stack trace are kept in the subprocess' error. 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).917918 [More info.](https://nodejs.org/api/child_process.html#subprocesskillsignal)919 */920 kill(signal: Parameters<ChildProcess['kill']>[0], error?: Error): ReturnType<ChildProcess['kill']>;921 kill(error?: Error): ReturnType<ChildProcess['kill']>;922} & PipableProcess;922} & PipableSubprocess;923924export type ExecaChildProcess<OptionsType extends Options = Options> = ChildProcess &925ExecaChildPromise<OptionsType> &926Promise<ExecaReturnValue<OptionsType>>;924export type ExecaSubprocess<OptionsType extends Options = Options> = ChildProcess &925ExecaResultPromise<OptionsType> &926Promise<ExecaResult<OptionsType>>;927928/**929Executes a command using `file ...arguments`.930
2 unmodified lines
933This is the preferred method when executing single commands.934935@param file - The program/script to execute, as a string or file URL936@param arguments - Arguments to pass to `file` on execution.937@returns An `ExecaChildProcess` that is both:938- a `Promise` resolving or rejecting with a `childProcessResult`.937@returns An `ExecaSubprocess` that is both:938- a `Promise` resolving or rejecting with a `subprocessResult`.939- a [`child_process` instance](https://nodejs.org/api/child_process.html#child_process_class_childprocess) with some additional methods and properties.940@throws A `childProcessResult` error940@throws A `subprocessResult` error941942@example <caption>Promise interface</caption>943```944import {execa} from 'execa';
26 unmodified lines
971console.log(stdout);972//=> 'unicorns'973```974975@example <caption>Save and pipe output from a child process</caption>975@example <caption>Save and pipe output from a subprocess</caption>976```977import {execa} from 'execa';978979const {stdout} = await execa('echo', ['unicorns'], {stdout: ['pipe', 'inherit']});
1 unmodified line
981console.log(stdout);982// Also returns 'unicorns'983```984985@example <caption>Pipe multiple processes</caption>985@example <caption>Pipe multiple subprocesses</caption>986```987import {execa} from 'execa';988989// Similar to `echo unicorns | cat` in Bash
41 unmodified lines
1031export function execa<OptionsType extends Options = {}>(1032 file: string | URL,1033 arguments?: readonly string[],1034 options?: OptionsType,1035): ExecaChildProcess<OptionsType>;1035): ExecaSubprocess<OptionsType>;1036export function execa<OptionsType extends Options = {}>(1037 file: string | URL,1038 options?: OptionsType,1039): ExecaChildProcess<OptionsType>;1039): ExecaSubprocess<OptionsType>;10401041/**1042Same as `execa()` but synchronous.10431044Cannot use the following options: `all`, `cleanup`, `buffer`, `detached`, `ipc`, `serialization`, `cancelSignal`, `lines` and `verbose: 'full'`. Also, the `stdin`, `stdout`, `stderr`, `stdio` and `input` options cannot be an array, an iterable, a transform or a web stream. Node.js streams must have a file descriptor unless the `input` option is used.10451046Returns or throws a `childProcessResult`. The `childProcess` is not returned: its methods and properties are not available. This includes [`.kill()`](https://nodejs.org/api/child_process.html#subprocesskillsignal), [`.pid`](https://nodejs.org/api/child_process.html#subprocesspid), `.pipe()` and the [`.stdin`/`.stdout`/`.stderr`](https://nodejs.org/api/child_process.html#subprocessstdout) streams.1046Returns or throws a `subprocessResult`. The `subprocess` is not returned: its methods and properties are not available. This includes [`.kill()`](https://nodejs.org/api/child_process.html#subprocesskillsignal), [`.pid`](https://nodejs.org/api/child_process.html#subprocesspid), `.pipe()` and the [`.stdin`/`.stdout`/`.stderr`](https://nodejs.org/api/child_process.html#subprocessstdout) streams.10471048@param file - The program/script to execute, as a string or file URL1049@param arguments - Arguments to pass to `file` on execution.1050@returns A `childProcessResult` object1051@throws A `childProcessResult` error1050@returns A `subprocessResult` object1051@throws A `subprocessResult` error10521053@example <caption>Promise interface</caption>1054```1055import {execa} from 'execa';
49 unmodified lines
1105export function execaSync<OptionsType extends SyncOptions = {}>(1106 file: string | URL,1107 arguments?: readonly string[],1108 options?: OptionsType,1109): ExecaSyncReturnValue<OptionsType>;1109): ExecaSyncResult<OptionsType>;1110export function execaSync<OptionsType extends SyncOptions = {}>(1111 file: string | URL,1112 options?: OptionsType,1113): ExecaSyncReturnValue<OptionsType>;1113): ExecaSyncResult<OptionsType>;11141115/**1116Executes a command. The `command` string includes both the `file` and its `arguments`.1117
1 unmodified line
11191120This is the preferred method when executing a user-supplied `command` string, such as in a REPL.11211122@param command - The program/script to execute and its arguments.1123@returns An `ExecaChildProcess` that is both:1124- a `Promise` resolving or rejecting with a `childProcessResult`.1123@returns An `ExecaSubprocess` that is both:1124- a `Promise` resolving or rejecting with a `subprocessResult`.1125- a [`child_process` instance](https://nodejs.org/api/child_process.html#child_process_class_childprocess) with some additional methods and properties.1126@throws A `childProcessResult` error1126@throws A `subprocessResult` error11271128@example1129```1130import {execaCommand} from 'execa';
5 unmodified lines
1136*/1137export function execaCommand<OptionsType extends Options = {}>(1138 command: string,1139 options?: OptionsType1140): ExecaChildProcess<OptionsType>;1140): ExecaSubprocess<OptionsType>;11411142/**1143Same as `execaCommand()` but synchronous.11441145Cannot use the following options: `all`, `cleanup`, `buffer`, `detached`, `ipc`, `serialization`, `cancelSignal`, `lines` and `verbose: 'full'`. Also, the `stdin`, `stdout`, `stderr`, `stdio` and `input` options cannot be an array, an iterable, a transform or a web stream. Node.js streams must have a file descriptor unless the `input` option is used.11461147Returns or throws a `childProcessResult`. The `childProcess` is not returned: its methods and properties are not available. This includes [`.kill()`](https://nodejs.org/api/child_process.html#subprocesskillsignal), [`.pid`](https://nodejs.org/api/child_process.html#subprocesspid), `.pipe()` and the [`.stdin`/`.stdout`/`.stderr`](https://nodejs.org/api/child_process.html#subprocessstdout) streams.1147Returns or throws a `subprocessResult`. The `subprocess` is not returned: its methods and properties are not available. This includes [`.kill()`](https://nodejs.org/api/child_process.html#subprocesskillsignal), [`.pid`](https://nodejs.org/api/child_process.html#subprocesspid), `.pipe()` and the [`.stdin`/`.stdout`/`.stderr`](https://nodejs.org/api/child_process.html#subprocessstdout) streams.11481149@param command - The program/script to execute and its arguments.1150@returns A `childProcessResult` object1151@throws A `childProcessResult` error1150@returns A `subprocessResult` object1151@throws A `subprocessResult` error11521153@example1154```1155import {execaCommandSync} from 'execa';
5 unmodified lines
1161*/1162export function execaCommandSync<OptionsType extends SyncOptions = {}>(1163 command: string,1164 options?: OptionsType1165): ExecaSyncReturnValue<OptionsType>;1165): ExecaSyncResult<OptionsType>;11661167type TemplateExpression = string | number | ExecaCommonReturnValue1168| Array<string | number | ExecaCommonReturnValue>;1167type TemplateExpression = string | number | ExecaCommonResult1168| Array<string | number | ExecaCommonResult>;11691170type Execa$<OptionsType extends CommonOptions = {}> = {1171 /**1172 Returns a new instance of `$` but with different default `options`. Consecutive calls are merged to previous ones.
21 unmodified lines
1194 <NewOptionsType extends CommonOptions = {}>1195 (options: NewOptionsType): Execa$<OptionsType & NewOptionsType>;11961197 (templates: TemplateStringsArray, ...expressions: readonly TemplateExpression[]):1198 ExecaChildProcess<StricterOptions<OptionsType, Options>> & PipableProcess;1198 ExecaSubprocess<StricterOptions<OptionsType, Options>> & PipableSubprocess;11991200 /**1201 Same as $\`command\` but synchronous.12021203 Cannot use the following options: `all`, `cleanup`, `buffer`, `detached`, `ipc`, `serialization`, `cancelSignal`, `lines` and `verbose: 'full'`. Also, the `stdin`, `stdout`, `stderr`, `stdio` and `input` options cannot be an array, an iterable, a transform or a web stream. Node.js streams must have a file descriptor unless the `input` option is used.12041205 Returns or throws a `childProcessResult`. The `childProcess` is not returned: its methods and properties are not available. This includes [`.kill()`](https://nodejs.org/api/child_process.html#subprocesskillsignal), [`.pid`](https://nodejs.org/api/child_process.html#subprocesspid), `.pipe()` and the [`.stdin`/`.stdout`/`.stderr`](https://nodejs.org/api/child_process.html#subprocessstdout) streams.1205 Returns or throws a `subprocessResult`. The `subprocess` is not returned: its methods and properties are not available. This includes [`.kill()`](https://nodejs.org/api/child_process.html#subprocesskillsignal), [`.pid`](https://nodejs.org/api/child_process.html#subprocesspid), `.pipe()` and the [`.stdin`/`.stdout`/`.stderr`](https://nodejs.org/api/child_process.html#subprocessstdout) streams.12061207 @returns A `childProcessResult` object1208 @throws A `childProcessResult` error1207 @returns A `subprocessResult` object1208 @throws A `subprocessResult` error12091210 @example <caption>Basic</caption>1211 ```1212 import {$} from 'execa';
35 unmodified lines
1248 */1249 sync(1250 templates: TemplateStringsArray,1251 ...expressions: readonly TemplateExpression[]1252 ): ExecaSyncReturnValue<StricterOptions<OptionsType, SyncOptions>>;1252 ): ExecaSyncResult<StricterOptions<OptionsType, SyncOptions>>;12531254 /**1255 Same as $\`command\` but synchronous.12561257 Cannot use the following options: `all`, `cleanup`, `buffer`, `detached`, `ipc`, `serialization`, `cancelSignal`, `lines` and `verbose: 'full'`. Also, the `stdin`, `stdout`, `stderr`, `stdio` and `input` options cannot be an array, an iterable, a transform or a web stream. Node.js streams must have a file descriptor unless the `input` option is used.12581259 Returns or throws a `childProcessResult`. The `childProcess` is not returned: its methods and properties are not available. This includes [`.kill()`](https://nodejs.org/api/child_process.html#subprocesskillsignal), [`.pid`](https://nodejs.org/api/child_process.html#subprocesspid), `.pipe()` and the [`.stdin`/`.stdout`/`.stderr`](https://nodejs.org/api/child_process.html#subprocessstdout) streams.1259 Returns or throws a `subprocessResult`. The `subprocess` is not returned: its methods and properties are not available. This includes [`.kill()`](https://nodejs.org/api/child_process.html#subprocesskillsignal), [`.pid`](https://nodejs.org/api/child_process.html#subprocesspid), `.pipe()` and the [`.stdin`/`.stdout`/`.stderr`](https://nodejs.org/api/child_process.html#subprocessstdout) streams.12601261 @returns A `childProcessResult` object1262 @throws A `childProcessResult` error1261 @returns A `subprocessResult` object1262 @throws A `subprocessResult` error12631264 @example <caption>Basic</caption>1265 ```1266 import {$} from 'execa';
35 unmodified lines
1302 */1303 s(1304 templates: TemplateStringsArray,1305 ...expressions: readonly TemplateExpression[]1306 ): ExecaSyncReturnValue<StricterOptions<OptionsType, SyncOptions>>;1306 ): ExecaSyncResult<StricterOptions<OptionsType, SyncOptions>>;1307};13081309/**1310Executes a command. The `command` string includes both the `file` and its `arguments`.
1 unmodified line
1312Arguments are automatically escaped. They can contain any character, but spaces, tabs and newlines must use `${}` like `` $`echo ${'has space'}` ``.13131314This is the preferred method when executing multiple commands in a script file.13151316The `command` string can inject any `${value}` with the following types: string, number, `childProcess` or an array of those types. For example: `` $`echo one ${'two'} ${3} ${['four', 'five']}` ``. For `${childProcess}`, the process's `stdout` is used.1316The `command` string can inject any `${value}` with the following types: string, number, `subprocess` or an array of those types. For example: `` $`echo one ${'two'} ${3} ${['four', 'five']}` ``. For `${subprocess}`, the subprocess's `stdout` is used.13171318@returns An `ExecaChildProcess` that is both:1319 - a `Promise` resolving or rejecting with a `childProcessResult`.1318@returns An `ExecaSubprocess` that is both:1319 - a `Promise` resolving or rejecting with a `subprocessResult`.1320 - a [`child_process` instance](https://nodejs.org/api/child_process.html#child_process_class_childprocess) with some additional methods and properties.1321@throws A `childProcessResult` error1321@throws A `subprocessResult` error13221323@example <caption>Basic</caption>1324```1325import {$} from 'execa';
43 unmodified lines
1369This is the preferred method when executing Node.js files.13701371@param scriptPath - Node.js script to execute, as a string or file URL1372@param arguments - Arguments to pass to `scriptPath` on execution.1373@returns An `ExecaChildProcess` that is both:1374- a `Promise` resolving or rejecting with a `childProcessResult`.1373@returns An `ExecaSubprocess` that is both:1374- a `Promise` resolving or rejecting with a `subprocessResult`.1375- a [`child_process` instance](https://nodejs.org/api/child_process.html#child_process_class_childprocess) with some additional methods and properties.1376@throws A `childProcessResult` error1376@throws A `subprocessResult` error13771378@example1379```1380import {execa} from 'execa';
4 unmodified lines
1385export function execaNode<OptionsType extends Options = {}>(1386 scriptPath: string | URL,1387 arguments?: readonly string[],1388 options?: OptionsType1389): ExecaChildProcess<OptionsType>;1389): ExecaSubprocess<OptionsType>;1390export function execaNode<OptionsType extends Options = {}>(1391 scriptPath: string | URL,1392 options?: OptionsType1393): ExecaChildProcess<OptionsType>;1393): ExecaSubprocess<OptionsType>;
modified:index.test-d.ts+62 added-62 removed
11 unmodified lines
12 execaCommand,13 execaCommandSync,14 execaNode,15 type Options,16 type ExecaReturnValue,17 type ExecaChildProcess,16 type ExecaResult,17 type ExecaSubprocess,18 type ExecaError,19 type SyncOptions,20 type ExecaSyncReturnValue,20 type ExecaSyncResult,21 type ExecaSyncError,22} from './index.js';2324const fileUrl = new URL('file:///test');2526type AnySyncChunk = string | Uint8Array | undefined;27type AnyChunk = AnySyncChunk | string[] | Uint8Array[] | unknown[];28expectType<Writable | null>({} as ExecaChildProcess['stdin']);29expectType<Readable | null>({} as ExecaChildProcess['stdout']);30expectType<Readable | null>({} as ExecaChildProcess['stderr']);31expectType<Readable | undefined>({} as ExecaChildProcess['all']);32expectType<AnyChunk>({} as ExecaReturnValue['stdout']);33expectType<AnyChunk>({} as ExecaReturnValue['stderr']);34expectType<AnyChunk>({} as ExecaReturnValue['all']);35expectType<[undefined, AnyChunk, AnyChunk]>({} as ExecaReturnValue['stdio']);36expectType<AnySyncChunk>({} as ExecaSyncReturnValue['stdout']);37expectType<AnySyncChunk>({} as ExecaSyncReturnValue['stderr']);38expectType<[undefined, AnySyncChunk, AnySyncChunk]>({} as ExecaSyncReturnValue['stdio']);28expectType<Writable | null>({} as ExecaSubprocess['stdin']);29expectType<Readable | null>({} as ExecaSubprocess['stdout']);30expectType<Readable | null>({} as ExecaSubprocess['stderr']);31expectType<Readable | undefined>({} as ExecaSubprocess['all']);32expectType<AnyChunk>({} as ExecaResult['stdout']);33expectType<AnyChunk>({} as ExecaResult['stderr']);34expectType<AnyChunk>({} as ExecaResult['all']);35expectType<[undefined, AnyChunk, AnyChunk]>({} as ExecaResult['stdio']);36expectType<AnySyncChunk>({} as ExecaSyncResult['stdout']);37expectType<AnySyncChunk>({} as ExecaSyncResult['stderr']);38expectType<[undefined, AnySyncChunk, AnySyncChunk]>({} as ExecaSyncResult['stdio']);3940const objectGenerator = function * (line: unknown) {41 yield JSON.parse(line as string) as object;42};
47 unmodified lines
9091 const pipeOptions = {from: 'stderr', all: true} as const;9293 type BufferExecaReturnValue = typeof bufferResult;94 type EmptyExecaReturnValue = ExecaReturnValue<{}>;95 type ShortcutExecaReturnValue = ExecaReturnValue<typeof pipeOptions>;94 type EmptyExecaReturnValue = ExecaResult<{}>;95 type ShortcutExecaReturnValue = ExecaResult<typeof pipeOptions>;9697 expectType<BufferExecaReturnValue>(await execaPromise.pipe(execaBufferPromise));98 expectType<BufferExecaReturnValue>(await scriptPromise.pipe(execaBufferPromise));99 expectNotType<BufferExecaReturnValue>(await execaPromise.pipe(execaPromise));
155 unmodified lines
255 expectType<string | undefined>(unicornsResult.signal);256 expectType<string | undefined>(unicornsResult.signalDescription);257 expectType<string>(unicornsResult.cwd);258 expectType<number>(unicornsResult.durationMs);259 expectType<ExecaReturnValue[]>(unicornsResult.pipedFrom);259 expectType<ExecaResult[]>(unicornsResult.pipedFrom);260261 expectType<undefined>(unicornsResult.stdio[0]);262 expectType<string>(unicornsResult.stdout);263 expectType<string>(unicornsResult.stdio[1]);
306 unmodified lines
570 expectType<string>(execaError.cwd);571 expectType<number>(execaError.durationMs);572 expectType<string>(execaError.shortMessage);573 expectType<string | undefined>(execaError.originalMessage);574 expectType<ExecaReturnValue[]>(execaError.pipedFrom);574 expectType<ExecaResult[]>(execaError.pipedFrom);575576 expectType<undefined>(execaError.stdio[0]);577578 const noAllError = error as ExecaError<{}>;
125 unmodified lines
704705try {706 const unicornsResult = execaSync('unicorns');707708 expectAssignable<ExecaSyncReturnValue>(unicornsResult);708 expectAssignable<ExecaSyncResult>(unicornsResult);709 expectType<string>(unicornsResult.command);710 expectType<string>(unicornsResult.escapedCommand);711 expectType<number | undefined>(unicornsResult.exitCode);712 expectError(unicornsResult.pipe);
754 unmodified lines
1467expectError(execa('unicorns').kill('SIGKILL', {}));1468expectError(execa('unicorns').kill(null, new Error('test')));14691470expectError(execa(['unicorns', 'arg']));1471expectAssignable<ExecaChildProcess>(execa('unicorns'));1472expectAssignable<ExecaChildProcess>(execa(fileUrl));1473expectType<ExecaReturnValue>(await execa('unicorns'));1471expectAssignable<ExecaSubprocess>(execa('unicorns'));1472expectAssignable<ExecaSubprocess>(execa(fileUrl));1473expectType<ExecaResult>(await execa('unicorns'));1474expectAssignable<{stdout: string}>(await execa('unicorns'));1475expectAssignable<{stdout: Uint8Array}>(await execa('unicorns', {encoding: 'buffer'}));1476expectAssignable<{stdout: string}>(await execa('unicorns', ['foo']));1477expectAssignable<{stdout: Uint8Array}>(await execa('unicorns', ['foo'], {encoding: 'buffer'}));14781479expectError(execaSync(['unicorns', 'arg']));1480expectAssignable<ExecaSyncReturnValue>(execaSync('unicorns'));1481expectAssignable<ExecaSyncReturnValue>(execaSync(fileUrl));1480expectAssignable<ExecaSyncResult>(execaSync('unicorns'));1481expectAssignable<ExecaSyncResult>(execaSync(fileUrl));1482expectAssignable<{stdout: string}>(execaSync('unicorns'));1483expectAssignable<{stdout: Uint8Array}>(execaSync('unicorns', {encoding: 'buffer'}));1484expectAssignable<{stdout: string}>(execaSync('unicorns', ['foo']));1485expectAssignable<{stdout: Uint8Array}>(execaSync('unicorns', ['foo'], {encoding: 'buffer'}));14861487expectAssignable<ExecaChildProcess>(execaCommand('unicorns'));1488expectType<ExecaReturnValue>(await execaCommand('unicorns'));1487expectAssignable<ExecaSubprocess>(execaCommand('unicorns'));1488expectType<ExecaResult>(await execaCommand('unicorns'));1489expectAssignable<{stdout: string}>(await execaCommand('unicorns'));1490expectAssignable<{stdout: Uint8Array}>(await execaCommand('unicorns', {encoding: 'buffer'}));1491expectAssignable<{stdout: string}>(await execaCommand('unicorns foo'));1492expectAssignable<{stdout: Uint8Array}>(await execaCommand('unicorns foo', {encoding: 'buffer'}));14931494expectAssignable<ExecaSyncReturnValue>(execaCommandSync('unicorns'));1494expectAssignable<ExecaSyncResult>(execaCommandSync('unicorns'));1495expectAssignable<{stdout: string}>(execaCommandSync('unicorns'));1496expectAssignable<{stdout: Uint8Array}>(execaCommandSync('unicorns', {encoding: 'buffer'}));1497expectAssignable<{stdout: string}>(execaCommandSync('unicorns foo'));1498expectAssignable<{stdout: Uint8Array}>(execaCommandSync('unicorns foo', {encoding: 'buffer'}));14991500expectError(execaNode(['unicorns', 'arg']));1501expectAssignable<ExecaChildProcess>(execaNode('unicorns'));1502expectType<ExecaReturnValue>(await execaNode('unicorns'));1503expectType<ExecaReturnValue>(await execaNode(fileUrl));1501expectAssignable<ExecaSubprocess>(execaNode('unicorns'));1502expectType<ExecaResult>(await execaNode('unicorns'));1503expectType<ExecaResult>(await execaNode(fileUrl));1504expectAssignable<{stdout: string}>(await execaNode('unicorns'));1505expectAssignable<{stdout: Uint8Array}>(await execaNode('unicorns', {encoding: 'buffer'}));1506expectAssignable<{stdout: string}>(await execaNode('unicorns', ['foo']));1507expectAssignable<{stdout: Uint8Array}>(await execaNode('unicorns', ['foo'], {encoding: 'buffer'}));15081509expectAssignable<ExecaChildProcess>(execaNode('unicorns', {nodePath: './node'}));1510expectAssignable<ExecaChildProcess>(execaNode('unicorns', {nodePath: fileUrl}));1509expectAssignable<ExecaSubprocess>(execaNode('unicorns', {nodePath: './node'}));1510expectAssignable<ExecaSubprocess>(execaNode('unicorns', {nodePath: fileUrl}));15111512expectAssignable<{stdout: string}>(await execaNode('unicorns', {nodeOptions: ['--async-stack-traces']}));1513expectAssignable<{stdout: Uint8Array}>(await execaNode('unicorns', {nodeOptions: ['--async-stack-traces'], encoding: 'buffer'}));1514expectAssignable<{stdout: string}>(await execaNode('unicorns', ['foo'], {nodeOptions: ['--async-stack-traces']}));1515expectAssignable<{stdout: Uint8Array}>(await execaNode('unicorns', ['foo'], {nodeOptions: ['--async-stack-traces'], encoding: 'buffer'}));15161517expectAssignable<ExecaChildProcess>($`unicorns`);1518expectAssignable<ExecaReturnValue>(await $`unicorns`);1519expectAssignable<ExecaSyncReturnValue>($.sync`unicorns`);1520expectAssignable<ExecaSyncReturnValue>($.s`unicorns`);1517expectAssignable<ExecaSubprocess>($`unicorns`);1518expectAssignable<ExecaResult>(await $`unicorns`);1519expectAssignable<ExecaSyncResult>($.sync`unicorns`);1520expectAssignable<ExecaSyncResult>($.s`unicorns`);15211522expectAssignable<ExecaChildProcess>($({})`unicorns`);1522expectAssignable<ExecaSubprocess>($({})`unicorns`);1523expectAssignable<{stdout: string}>(await $({})`unicorns`);1524expectAssignable<{stdout: string}>($({}).sync`unicorns`);15251526expectAssignable<ExecaChildProcess>($({})`unicorns foo`);1526expectAssignable<ExecaSubprocess>($({})`unicorns foo`);1527expectAssignable<{stdout: string}>(await $({})`unicorns foo`);1528expectAssignable<{stdout: string}>($({}).sync`unicorns foo`);15291530expectAssignable<ExecaChildProcess>($({encoding: 'buffer'})`unicorns`);1530expectAssignable<ExecaSubprocess>($({encoding: 'buffer'})`unicorns`);1531expectAssignable<{stdout: Uint8Array}>(await $({encoding: 'buffer'})`unicorns`);1532expectAssignable<{stdout: Uint8Array}>($({encoding: 'buffer'}).sync`unicorns`);15331534expectAssignable<ExecaChildProcess>($({encoding: 'buffer'})`unicorns foo`);1534expectAssignable<ExecaSubprocess>($({encoding: 'buffer'})`unicorns foo`);1535expectAssignable<{stdout: Uint8Array}>(await $({encoding: 'buffer'})`unicorns foo`);1536expectAssignable<{stdout: Uint8Array}>($({encoding: 'buffer'}).sync`unicorns foo`);15371538expectAssignable<ExecaChildProcess>($({encoding: 'buffer'})({})`unicorns`);1538expectAssignable<ExecaSubprocess>($({encoding: 'buffer'})({})`unicorns`);1539expectAssignable<{stdout: Uint8Array}>(await $({encoding: 'buffer'})({})`unicorns`);1540expectAssignable<{stdout: Uint8Array}>($({encoding: 'buffer'})({}).sync`unicorns`);15411542expectAssignable<ExecaChildProcess>($({encoding: 'buffer'})({})`unicorns foo`);1542expectAssignable<ExecaSubprocess>($({encoding: 'buffer'})({})`unicorns foo`);1543expectAssignable<{stdout: Uint8Array}>(await $({encoding: 'buffer'})({})`unicorns foo`);1544expectAssignable<{stdout: Uint8Array}>($({encoding: 'buffer'})({}).sync`unicorns foo`);15451546expectAssignable<ExecaChildProcess>($({})({encoding: 'buffer'})`unicorns`);1546expectAssignable<ExecaSubprocess>($({})({encoding: 'buffer'})`unicorns`);1547expectAssignable<{stdout: Uint8Array}>(await $({})({encoding: 'buffer'})`unicorns`);1548expectAssignable<{stdout: Uint8Array}>($({})({encoding: 'buffer'}).sync`unicorns`);15491550expectAssignable<ExecaChildProcess>($({})({encoding: 'buffer'})`unicorns foo`);1550expectAssignable<ExecaSubprocess>($({})({encoding: 'buffer'})`unicorns foo`);1551expectAssignable<{stdout: Uint8Array}>(await $({})({encoding: 'buffer'})`unicorns foo`);1552expectAssignable<{stdout: Uint8Array}>($({})({encoding: 'buffer'}).sync`unicorns foo`);15531554expectAssignable<ExecaReturnValue>(await $`unicorns ${'foo'}`);1555expectAssignable<ExecaSyncReturnValue>($.sync`unicorns ${'foo'}`);1556expectAssignable<ExecaReturnValue>(await $`unicorns ${1}`);1557expectAssignable<ExecaSyncReturnValue>($.sync`unicorns ${1}`);1558expectAssignable<ExecaReturnValue>(await $`unicorns ${['foo', 'bar']}`);1559expectAssignable<ExecaSyncReturnValue>($.sync`unicorns ${['foo', 'bar']}`);1560expectAssignable<ExecaReturnValue>(await $`unicorns ${[1, 2]}`);1561expectAssignable<ExecaSyncReturnValue>($.sync`unicorns ${[1, 2]}`);1562expectAssignable<ExecaReturnValue>(await $`unicorns ${await $`echo foo`}`);1563expectError<ExecaReturnValue>(await $`unicorns ${$`echo foo`}`);1564expectAssignable<ExecaSyncReturnValue>($.sync`unicorns ${$.sync`echo foo`}`);1565expectAssignable<ExecaReturnValue>(await $`unicorns ${[await $`echo foo`, 'bar']}`);1566expectError<ExecaReturnValue>(await $`unicorns ${[$`echo foo`, 'bar']}`);1567expectAssignable<ExecaSyncReturnValue>($.sync`unicorns ${[$.sync`echo foo`, 'bar']}`);1568expectAssignable<ExecaReturnValue>(await $`unicorns ${true.toString()}`);1569expectAssignable<ExecaSyncReturnValue>($.sync`unicorns ${false.toString()}`);1570expectError<ExecaReturnValue>(await $`unicorns ${true}`);1571expectError<ExecaSyncReturnValue>($.sync`unicorns ${false}`);1554expectAssignable<ExecaResult>(await $`unicorns ${'foo'}`);1555expectAssignable<ExecaSyncResult>($.sync`unicorns ${'foo'}`);1556expectAssignable<ExecaResult>(await $`unicorns ${1}`);1557expectAssignable<ExecaSyncResult>($.sync`unicorns ${1}`);1558expectAssignable<ExecaResult>(await $`unicorns ${['foo', 'bar']}`);1559expectAssignable<ExecaSyncResult>($.sync`unicorns ${['foo', 'bar']}`);1560expectAssignable<ExecaResult>(await $`unicorns ${[1, 2]}`);1561expectAssignable<ExecaSyncResult>($.sync`unicorns ${[1, 2]}`);1562expectAssignable<ExecaResult>(await $`unicorns ${await $`echo foo`}`);1563expectError<ExecaResult>(await $`unicorns ${$`echo foo`}`);1564expectAssignable<ExecaSyncResult>($.sync`unicorns ${$.sync`echo foo`}`);1565expectAssignable<ExecaResult>(await $`unicorns ${[await $`echo foo`, 'bar']}`);1566expectError<ExecaResult>(await $`unicorns ${[$`echo foo`, 'bar']}`);1567expectAssignable<ExecaSyncResult>($.sync`unicorns ${[$.sync`echo foo`, 'bar']}`);1568expectAssignable<ExecaResult>(await $`unicorns ${true.toString()}`);1569expectAssignable<ExecaSyncResult>($.sync`unicorns ${false.toString()}`);1570expectError<ExecaResult>(await $`unicorns ${true}`);1571expectError<ExecaSyncResult>($.sync`unicorns ${false}`);
modified:package.json+1 added
29 unmodified lines
30 "keywords": [31 "exec",32 "child",33 "process",34 "subprocess",35 "execute",36 "fork",37 "execfile",38 "spawn",
60 unmodified lines
modified:readme.md+93 added-93 removed
49 unmodified lines
50- [Promise interface](#execacommandcommand-options).51- [Scripts interface](#scripts-interface), like `zx`.52- Improved [Windows support](https://github.com/IndigoUnited/node-cross-spawn#why), including [shebang](https://en.wikipedia.org/wiki/Shebang_(Unix)) binaries.53- Executes [locally installed binaries](#preferlocal) without `npx`.54- [Cleans up](#cleanup) child processes when the parent process ends.54- [Cleans up](#cleanup) subprocesses when the current process ends.55- Redirect [`stdin`](#stdin)/[`stdout`](#stdout-1)/[`stderr`](#stderr-1) from/to files, streams, iterables, strings, `Uint8Array` or [objects](docs/transform.md#object-mode).56- [Transform](docs/transform.md) `stdin`/`stdout`/`stderr` with simple functions.57- Iterate over [each text line](docs/transform.md#binary-data) output by the process.58- [Fail-safe process termination](#forcekillafterdelay).57- Iterate over [each text line](docs/transform.md#binary-data) output by the subprocess.58- [Fail-safe subprocess termination](#forcekillafterdelay).59- Get [interleaved output](#all) from `stdout` and `stderr` similar to what is printed on the terminal.60- [Strips the final newline](#stripfinalnewline) from the output so you don't have to do `stdout.trim()`.61- Convenience methods to pipe processes' [input](#input) and [output](#redirect-output-to-a-file).61- Convenience methods to pipe subprocesses' [input](#input) and [output](#redirect-output-to-a-file).62- Can specify file and arguments [as a single string](#execacommandcommand-options) without a shell.63- [Verbose mode](#verbose-mode) for debugging.64- More descriptive errors.65- Higher max buffer: 100 MB instead of 1 MB.
116 unmodified lines
182console.log(stdout);183//=> 'unicorns'184```185186#### Save and pipe output from a child process186#### Save and pipe output from a subprocess187188```js189import {execa} from 'execa';190
2 unmodified lines
193console.log(stdout);194// Also returns 'unicorns'195```196197#### Pipe multiple processes197#### Pipe multiple subprocesses198199```js200import {execa} from 'execa';201
51 unmodified lines
253254`file`: `string | URL`\255`arguments`: `string[]`\256`options`: [`Options`](#options-1)\257_Returns_: [`ChildProcess`](#childprocess)257_Returns_: [`Subprocess`](#subprocess)258259Executes a command using `file ...arguments`.260261Arguments are [automatically escaped](#shell-syntax). They can contain any character, including spaces.
4 unmodified lines
266#### $(options)\`command\`267268`command`: `string`\269`options`: [`Options`](#options-1)\270_Returns_: [`ChildProcess`](#childprocess)270_Returns_: [`Subprocess`](#subprocess)271272Executes a command. The `command` string includes both the `file` and its `arguments`.273274Arguments are [automatically escaped](#shell-syntax). They can contain any character, but spaces, tabs and newlines must use `${}` like `` $`echo ${'has space'}` ``.275276This is the preferred method when executing multiple commands in a script file.277278The `command` string can inject any `${value}` with the following types: string, number, [`childProcess`](#childprocess) or an array of those types. For example: `` $`echo one ${'two'} ${3} ${['four', 'five']}` ``. For `${childProcess}`, the process's `stdout` is used.278The `command` string can inject any `${value}` with the following types: string, number, [`subprocess`](#subprocess) or an array of those types. For example: `` $`echo one ${'two'} ${3} ${['four', 'five']}` ``. For `${subprocess}`, the subprocess's `stdout` is used.279280The `command` string can use [multiple lines and indentation](docs/scripts.md#multiline-commands).281282For more information, please see [this section](#scripts-interface) and [this page](docs/scripts.md).
12 unmodified lines
295#### execaCommand(command, options?)296297`command`: `string`\298`options`: [`Options`](#options-1)\299_Returns_: [`ChildProcess`](#childprocess)299_Returns_: [`Subprocess`](#subprocess)300301Executes a command. The `command` string includes both the `file` and its `arguments`.302303Arguments are [automatically escaped](#shell-syntax). They can contain any character, but spaces must be escaped with a backslash like `execaCommand('echo has\\ space')`.
4 unmodified lines
308309`file`: `string | URL`\310`arguments`: `string[]`\311`options`: [`Options`](#options-1)\312_Returns_: [`ChildProcess`](#childprocess)312_Returns_: [`Subprocess`](#subprocess)313314Same as [`execa()`](#execacommandcommand-options) but using the [`node`](#node) option.315316Executes a Node.js file using `node scriptPath ...arguments`.
10 unmodified lines
327Same as [`execa()`](#execacommandcommand-options), [`execaCommand()`](#execacommand-command-options), [$\`command\`](#command) but synchronous.328329Cannot use the following options: [`all`](#all-2), [`cleanup`](#cleanup), [`buffer`](#buffer), [`detached`](#detached), [`ipc`](#ipc), [`serialization`](#serialization), [`cancelSignal`](#cancelsignal), [`lines`](#lines) and [`verbose: 'full'`](#verbose). Also, the [`stdin`](#stdin), [`stdout`](#stdout-1), [`stderr`](#stderr-1), [`stdio`](#stdio-1) and [`input`](#input) options cannot be an array, an iterable, a [transform](docs/transform.md) or a web stream. Node.js streams [must have a file descriptor](#redirect-a-nodejs-stream-fromto-stdinstdoutstderr) unless the `input` option is used.330331Returns or throws a [`childProcessResult`](#childProcessResult). The [`childProcess`](#childprocess) is not returned: its methods and properties are not available. This includes [`.kill()`](https://nodejs.org/api/child_process.html#subprocesskillsignal), [`.pid`](https://nodejs.org/api/child_process.html#subprocesspid), [`.pipe()`](#pipefile-arguments-options) and the [`.stdin`/`.stdout`/`.stderr`](https://nodejs.org/api/child_process.html#subprocessstdout) streams.331Returns or throws a [`subprocessResult`](#subprocessResult). The [`subprocess`](#subprocess) is not returned: its methods and properties are not available. This includes [`.kill()`](https://nodejs.org/api/child_process.html#subprocesskillsignal), [`.pid`](https://nodejs.org/api/child_process.html#subprocesspid), [`.pipe()`](#pipefile-arguments-options) and the [`.stdin`/`.stdout`/`.stderr`](https://nodejs.org/api/child_process.html#subprocessstdout) streams.332333### Shell syntax334335For all the [methods above](#methods), no shell interpreter (Bash, cmd.exe, etc.) is used unless the [`shell` option](#shell) is set. This means shell-specific characters and expressions (`$variable`, `&&`, `||`, `;`, `|`, etc.) have no special meaning and do not need to be escaped.336337### childProcess337### subprocess338339The return value of all [asynchronous methods](#methods) is both:340- a `Promise` resolving or rejecting with a [`childProcessResult`](#childProcessResult).340- a `Promise` resolving or rejecting with a [`subprocessResult`](#subprocessResult).341- a [`child_process` instance](https://nodejs.org/api/child_process.html#child_process_class_childprocess) with the following additional methods and properties.342343#### all344
9 unmodified lines
354355`file`: `string | URL`\356`arguments`: `string[]`\357`options`: [`Options`](#options-1) and [`PipeOptions`](#pipeoptions)\358_Returns_: [`Promise<ChildProcessResult>`](#childprocessresult)358_Returns_: [`Promise<SubprocessResult>`](#subprocessresult)359360[Pipe](https://nodejs.org/api/stream.html#readablepipedestination-options) the child process' `stdout` to a second Execa child process' `stdin`. This resolves with that second process' [result](#childprocessresult). If either process is rejected, this is rejected with that process' [error](#childprocessresult) instead.360[Pipe](https://nodejs.org/api/stream.html#readablepipedestination-options) the subprocess' `stdout` to a second Execa subprocess' `stdin`. This resolves with that second subprocess' [result](#subprocessresult). If either subprocess is rejected, this is rejected with that subprocess' [error](#subprocessresult) instead.361362This follows the same syntax as [`execa(file, arguments?, options?)`](#execafile-arguments-options) except both [regular options](#options-1) and [pipe-specific options](#pipeoptions) can be specified.363364This can be called multiple times to chain a series of processes.364This can be called multiple times to chain a series of subprocesses.365366Multiple child processes can be piped to the same process. Conversely, the same child process can be piped to multiple other processes.366Multiple subprocesses can be piped to the same subprocess. Conversely, the same subprocess can be piped to multiple other subprocesses.367368This is usually the preferred method to pipe processes.368This is usually the preferred method to pipe subprocesses.369370#### pipe\`command\`371#### pipe(options)\`command\`372373`command`: `string`\374`options`: [`Options`](#options-1) and [`PipeOptions`](#pipeoptions)\375_Returns_: [`Promise<ChildProcessResult>`](#childprocessresult)375_Returns_: [`Promise<SubprocessResult>`](#subprocessresult)376377Like [`.pipe(file, arguments?, options?)`](#pipefile-arguments-options) but using a [`command` template string](docs/scripts.md#piping-stdout-to-another-command) instead. This follows the same syntax as [`$`](#command).378379This is the preferred method to pipe processes when using [`$`](#command).379This is the preferred method to pipe subprocesses when using [`$`](#command).380381#### pipe(secondChildProcess, pipeOptions?)381#### pipe(secondSubprocess, pipeOptions?)382383`secondChildProcess`: [`execa()` return value](#childprocess)\383`secondSubprocess`: [`execa()` return value](#subprocess)\384`pipeOptions`: [`PipeOptions`](#pipeoptions)\385_Returns_: [`Promise<ChildProcessResult>`](#childprocessresult)385_Returns_: [`Promise<SubprocessResult>`](#subprocessresult)386387Like [`.pipe(file, arguments?, options?)`](#pipefile-arguments-options) but using the [return value](#childprocess) of another `execa()` call instead.387Like [`.pipe(file, arguments?, options?)`](#pipefile-arguments-options) but using the [return value](#subprocess) of another `execa()` call instead.388389This is the most advanced method to pipe processes. It is useful in specific cases, such as piping multiple child processes to the same process.389This is the most advanced method to pipe subprocesses. It is useful in specific cases, such as piping multiple subprocesses to the same subprocess.390391##### pipeOptions392393Type: `object`
10 unmodified lines
404##### pipeOptions.unpipeSignal405406Type: [`AbortSignal`](https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal)407408Unpipe the child process when the signal aborts.408Unpipe the subprocess when the signal aborts.409410The [`.pipe()`](#pipefile-arguments-options) method will be rejected with a cancellation error.411412#### kill(signal, error?)
2 unmodified lines
415`signal`: `string | number`\416`error`: `Error`\417_Returns_: `boolean`418419Sends a [signal](https://nodejs.org/api/os.html#signal-constants) to the child process. The default signal is the [`killSignal`](#killsignal) option. `killSignal` defaults to `SIGTERM`, which [terminates](#isterminated) the child process.419Sends a [signal](https://nodejs.org/api/os.html#signal-constants) to the subprocess. The default signal is the [`killSignal`](#killsignal) option. `killSignal` defaults to `SIGTERM`, which [terminates](#isterminated) the subprocess.420421This returns `false` when the signal could not be sent, for example when the child process has already exited.421This returns `false` when the signal could not be sent, for example when the subprocess has already exited.422423When an error is passed as argument, its message and stack trace are kept in the [child process' error](#childprocessresult). The child process is then terminated with the default signal. This does not emit the [`error` event](https://nodejs.org/api/child_process.html#event-error).423When an error is passed as argument, its message and stack trace are kept in the [subprocess' error](#subprocessresult). 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).424425[More info.](https://nodejs.org/api/child_process.html#subprocesskillsignal)426427### childProcessResult427### SubprocessResult428429Type: `object`430431Result of a child process execution. On success this is a plain object. On failure this is also an `Error` instance.431Result of a subprocess execution. On success this is a plain object. On failure this is also an `Error` instance.432433The child process [fails](#failed) when:433The subprocess [fails](#failed) when:434- its [exit code](#exitcode) is not `0`435- it was [terminated](#isterminated) with a [signal](#signal)436- [timing out](#timedout)437- [being canceled](#iscanceled)438- there's not enough memory or there are already too many child processes438- there's not enough memory or there are already too many subprocesses439440#### command441442Type: `string`443444The file and arguments that were run, for logging purposes.445446This is not escaped and should not be executed directly as a process, including using [`execa()`](#execafile-arguments-options) or [`execaCommand()`](#execacommandcommand-options).446This is not escaped and should not be executed directly as a subprocess, including using [`execa()`](#execafile-arguments-options) or [`execaCommand()`](#execacommandcommand-options).447448#### escapedCommand449450Type: `string`
2 unmodified lines
453454Unlike `command`, control characters are escaped, which makes it safe to print in a terminal.455456This can also be copied and pasted into a shell, for debugging purposes.457Since the escaping is fairly basic, this should not be executed directly as a process, including using [`execa()`](#execafile-arguments-options) or [`execaCommand()`](#execacommandcommand-options).457Since the escaping is fairly basic, this should not be executed directly as a subprocess, including using [`execa()`](#execafile-arguments-options) or [`execaCommand()`](#execacommandcommand-options).458459#### cwd460461Type: `string`
3 unmodified lines
465#### durationMs466467Type: `number`468469Duration of the child process, in milliseconds.469Duration of the subprocess, in milliseconds.470471#### stdout472473Type: `string | Uint8Array | string[] | Uint8Array[] | unknown[] | undefined`474475The output of the process on `stdout`.475The output of the subprocess on `stdout`.476477This is `undefined` if the [`stdout`](#stdout-1) option is set to only [`'inherit'`, `'ignore'`, `Stream` or `integer`](https://nodejs.org/api/child_process.html#child_process_options_stdio). This is an array if the [`lines` option](#lines) is `true`, or if the `stdout` option is a [transform in object mode](docs/transform.md#object-mode).478479#### stderr480481Type: `string | Uint8Array | string[] | Uint8Array[] | unknown[] | undefined`482483The output of the process on `stderr`.483The output of the subprocess on `stderr`.484485This is `undefined` if the [`stderr`](#stderr-1) option is set to only [`'inherit'`, `'ignore'`, `Stream` or `integer`](https://nodejs.org/api/child_process.html#child_process_options_stdio). This is an array if the [`lines` option](#lines) is `true`, or if the `stderr` option is a [transform in object mode](docs/transform.md#object-mode).486487#### all488489Type: `string | Uint8Array | string[] | Uint8Array[] | unknown[] | undefined`490491The output of the process with `stdout` and `stderr` [interleaved](#ensuring-all-output-is-interleaved).491The output of the subprocess with `stdout` and `stderr` [interleaved](#ensuring-all-output-is-interleaved).492493This is `undefined` if either:494- the [`all` option](#all-2) is `false` (the default value)495- both [`stdout`](#stdout-1) and [`stderr`](#stderr-1) options are set to only [`'inherit'`, `'ignore'`, `Stream` or `integer`](https://nodejs.org/api/child_process.html#child_process_options_stdio)
3 unmodified lines
499#### stdio500501Type: `Array<string | Uint8Array | string[] | Uint8Array[] | unknown[] | undefined>`502503The output of the process on [`stdin`](#stdin), [`stdout`](#stdout-1), [`stderr`](#stderr-1) and [other file descriptors](#stdio-1).503The output of the subprocess on [`stdin`](#stdin), [`stdout`](#stdout-1), [`stderr`](#stderr-1) and [other file descriptors](#stdio-1).504505Items are `undefined` when their corresponding [`stdio`](#stdio-1) option is set to [`'inherit'`, `'ignore'`, `Stream` or `integer`](https://nodejs.org/api/child_process.html#child_process_options_stdio). Items are arrays when their corresponding `stdio` option is a [transform in object mode](docs/transform.md#object-mode).506507#### message508509Type: `string`510511Error message when the child process failed to run. In addition to the [underlying error message](#originalMessage), it also contains some information related to why the child process errored.511Error message when the subprocess failed to run. In addition to the [underlying error message](#originalMessage), it also contains some information related to why the subprocess errored.512513The child process [`stderr`](#stderr), [`stdout`](#stdout) and other [file descriptors' output](#stdio) are appended to the end, separated with newlines and not interleaved.513The subprocess [`stderr`](#stderr), [`stdout`](#stdout) and other [file descriptors' output](#stdio) are appended to the end, separated with newlines and not interleaved.514515#### shortMessage516517Type: `string`518519This is the same as the [`message` property](#message) except it does not include the child process [`stdout`](#stdout)/[`stderr`](#stderr)/[`stdio`](#stdio).519This is the same as the [`message` property](#message) except it does not include the subprocess [`stdout`](#stdout)/[`stderr`](#stderr)/[`stdio`](#stdio).520521#### originalMessage522523Type: `string | undefined`524525Original error message. This is the same as the `message` property excluding the child process [`stdout`](#stdout)/[`stderr`](#stderr)/[`stdio`](#stdio) and some additional information added by Execa.525Original error message. This is the same as the `message` property excluding the subprocess [`stdout`](#stdout)/[`stderr`](#stderr)/[`stdio`](#stdio) and some additional information added by Execa.526527This is `undefined` unless the child process exited due to an `error` event or a timeout.527This is `undefined` unless the subprocess exited due to an `error` event or a timeout.528529#### failed530531Type: `boolean`532533Whether the process failed to run.533Whether the subprocess failed to run.534535#### timedOut536537Type: `boolean`538539Whether the process timed out.539Whether the subprocess timed out.540541#### isCanceled542543Type: `boolean`544545Whether the process was canceled using the [`cancelSignal`](#cancelsignal) option.545Whether the subprocess was canceled using the [`cancelSignal`](#cancelsignal) option.546547#### isTerminated548549Type: `boolean`550551Whether the process was terminated by a signal (like `SIGTERM`) sent by either:551Whether the subprocess was terminated by a signal (like `SIGTERM`) sent by either:552- The current process.553- Another process. This case is [not supported on Windows](https://nodejs.org/api/process.html#signal-events).554555#### exitCode556557Type: `number | undefined`558559The numeric exit code of the process that was run.559The numeric exit code of the subprocess that was run.560561This is `undefined` when the process could not be spawned or was terminated by a [signal](#signal).561This is `undefined` when the subprocess could not be spawned or was terminated by a [signal](#signal).562563#### signal564565Type: `string | undefined`566567The name of the signal (like `SIGTERM`) that terminated the process, sent by either:567The name of the signal (like `SIGTERM`) that terminated the subprocess, sent by either:568- The current process.569- Another process. This case is [not supported on Windows](https://nodejs.org/api/process.html#signal-events).570571If a signal terminated the process, this property is defined and included in the error message. Otherwise it is `undefined`.571If a signal terminated the subprocess, this property is defined and included in the error message. Otherwise it is `undefined`.572573#### signalDescription574575Type: `string | undefined`576577A human-friendly description of the signal that was used to terminate the process. For example, `Floating point arithmetic error`.577A human-friendly description of the signal that was used to terminate the subprocess. For example, `Floating point arithmetic error`.578579If a signal terminated the process, this property is defined and included in the error message. Otherwise it is `undefined`. It is also `undefined` when the signal is very uncommon which should seldomly happen.579If a signal terminated the subprocess, this property is defined and included in the error message. Otherwise it is `undefined`. It is also `undefined` when the signal is very uncommon which should seldomly happen.580581#### pipedFrom582583Type: [`ChildProcessResult[]`](#childprocessresult)583Type: [`SubprocessResult[]`](#subprocessresult)584585Results of the other processes that were [piped](#pipe-multiple-processes) into this child process. This is useful to inspect a series of child processes piped with each other.585Results of the other subprocesses that were [piped](#pipe-multiple-subprocesses) into this subprocess. This is useful to inspect a series of subprocesses piped with each other.586587This array is initially empty and is populated each time the [`.pipe()`](#pipefile-arguments-options) method resolves.588589### options
25 unmodified lines
615616Type: `string | URL`\617Default: `process.cwd()`618619Current working directory of the child process.619Current working directory of the subprocess.620621This is also used to resolve the [`nodePath`](#nodepath) option when it is a relative path.622623#### env
2 unmodified lines
626Default: `process.env`627628Environment key-value pairs.629630Unless the [`extendEnv` option](#extendenv) is `false`, the child process also uses the current process' environment variables ([`process.env`](https://nodejs.org/api/process.html#processenv)).630Unless the [`extendEnv` option](#extendenv) is `false`, the subprocess also uses the current process' environment variables ([`process.env`](https://nodejs.org/api/process.html#processenv)).631632#### extendEnv633634Type: `boolean`\635Default: `true`636637If `true`, the child process uses both the [`env` option](#env) and the current process' environment variables ([`process.env`](https://nodejs.org/api/process.html#processenv)).637If `true`, the subprocess uses both the [`env` option](#env) and the current process' environment variables ([`process.env`](https://nodejs.org/api/process.html#processenv)).638If `false`, only the `env` option is used, not `process.env`.639640#### preferLocal641
45 unmodified lines
687If `verbose` is `'short'` or `'full'`, [prints each command](#verbose-mode) on `stderr` before executing it. When the command completes, prints its duration and (if it failed) its error.688689If `verbose` is `'full'`, the command's `stdout` and `stderr` are printed too, unless either:690- the [`stdout`](#stdout-1)/[`stderr`](#stderr-1) option is `ignore` or `inherit`.691- the `stdout`/`stderr` is redirected to [a stream](https://nodejs.org/api/stream.html#readablepipedestination-options), [a file](#stdout-1), a file descriptor, or [another child process](#pipefile-arguments-options).691- the `stdout`/`stderr` is redirected to [a stream](https://nodejs.org/api/stream.html#readablepipedestination-options), [a file](#stdout-1), a file descriptor, or [another subprocess](#pipefile-arguments-options).692- the [`encoding`](#encoding) option is set.693694This can also be set to `'full'` by setting the `NODE_DEBUG=execa` environment variable in the current process.695
1 unmodified line
697698Type: `boolean`\699Default: `true`700701Whether to return the child process' output using the [`result.stdout`](#stdout), [`result.stderr`](#stderr), [`result.all`](#all-1) and [`result.stdio`](#stdio) properties.701Whether to return the subprocess' output using the [`result.stdout`](#stdout), [`result.stderr`](#stderr), [`result.all`](#all-1) and [`result.stdio`](#stdio) properties.702703On failure, the [`error.stdout`](#stdout), [`error.stderr`](#stderr), [`error.all`](#all-1) and [`error.stdio`](#stdio) properties are used instead.704705When `buffer` is `false`, the output can still be read using the [`childProcess.stdout`](#stdout-1), [`childProcess.stderr`](#stderr-1), [`childProcess.stdio`](https://nodejs.org/api/child_process.html#subprocessstdio) and [`childProcess.all`](#all) streams. If the output is read, this should be done right away to avoid missing any data.705When `buffer` is `false`, the output can still be read using the [`subprocess.stdout`](#stdout-1), [`subprocess.stderr`](#stderr-1), [`subprocess.stdio`](https://nodejs.org/api/child_process.html#subprocessstdio) and [`subprocess.all`](#all) streams. If the output is read, this should be done right away to avoid missing any data.706707#### input708709Type: `string | Uint8Array | stream.Readable`710711Write some input to the child process' `stdin`.711Write some input to the subprocess' `stdin`.712713See also the [`inputFile`](#inputfile) and [`stdin`](#stdin) options.714715#### inputFile716717Type: `string | URL`718719Use a file as input to the child process' `stdin`.719Use a file as input to the subprocess' `stdin`.720721See also the [`input`](#input) and [`stdin`](#stdin) options.722723#### stdin724725Type: `string | number | stream.Readable | ReadableStream | URL | Uint8Array | Iterable<string> | Iterable<Uint8Array> | Iterable<unknown> | AsyncIterable<string> | AsyncIterable<Uint8Array> | AsyncIterable<unknown> | GeneratorFunction<string> | GeneratorFunction<Uint8Array> | GeneratorFunction<unknown>| AsyncGeneratorFunction<string> | AsyncGeneratorFunction<Uint8Array> | AsyncGeneratorFunction<unknown>` (or a tuple of those types)\726Default: `inherit` with [`$`](#command), `pipe` otherwise727728[How to setup](https://nodejs.org/api/child_process.html#child_process_options_stdio) the child process' standard input. This can be:729- `'pipe'`: Sets [`childProcess.stdin`](https://nodejs.org/api/child_process.html#subprocessstdin) stream.728[How to setup](https://nodejs.org/api/child_process.html#child_process_options_stdio) the subprocess' standard input. This can be:729- `'pipe'`: Sets [`subprocess.stdin`](https://nodejs.org/api/child_process.html#subprocessstdin) stream.730- `'overlapped'`: Like `'pipe'` but asynchronous on Windows.731- `'ignore'`: Do not use `stdin`.732- `'inherit'`: Re-use the current process' `stdin`.733- an integer: Re-use a specific file descriptor from the current process.
12 unmodified lines
746747Type: `string | number | stream.Writable | WritableStream | URL | GeneratorFunction<string> | GeneratorFunction<Uint8Array> | GeneratorFunction<unknown>| AsyncGeneratorFunction<string> | AsyncGeneratorFunction<Uint8Array> | AsyncGeneratorFunction<unknown>` (or a tuple of those types)\748Default: `pipe`749750[How to setup](https://nodejs.org/api/child_process.html#child_process_options_stdio) the child process' standard output. This can be:751- `'pipe'`: Sets [`childProcessResult.stdout`](#stdout) (as a string or `Uint8Array`) and [`childProcess.stdout`](https://nodejs.org/api/child_process.html#subprocessstdout) (as a stream).750[How to setup](https://nodejs.org/api/child_process.html#child_process_options_stdio) the subprocess' standard output. This can be:751- `'pipe'`: Sets [`subprocessResult.stdout`](#stdout) (as a string or `Uint8Array`) and [`subprocess.stdout`](https://nodejs.org/api/child_process.html#subprocessstdout) (as a stream).752- `'overlapped'`: Like `'pipe'` but asynchronous on Windows.753- `'ignore'`: Do not use `stdout`.754- `'inherit'`: Re-use the current process' `stdout`.755- an integer: Re-use a specific file descriptor from the current process.
10 unmodified lines
766767Type: `string | number | stream.Writable | WritableStream | URL | GeneratorFunction<string> | GeneratorFunction<Uint8Array> | GeneratorFunction<unknown>| AsyncGeneratorFunction<string> | AsyncGeneratorFunction<Uint8Array> | AsyncGeneratorFunction<unknown>` (or a tuple of those types)\768Default: `pipe`769770[How to setup](https://nodejs.org/api/child_process.html#child_process_options_stdio) the child process' standard error. This can be:771- `'pipe'`: Sets [`childProcessResult.stderr`](#stderr) (as a string or `Uint8Array`) and [`childProcess.stderr`](https://nodejs.org/api/child_process.html#subprocessstderr) (as a stream).770[How to setup](https://nodejs.org/api/child_process.html#child_process_options_stdio) the subprocess' standard error. This can be:771- `'pipe'`: Sets [`subprocessResult.stderr`](#stderr) (as a string or `Uint8Array`) and [`subprocess.stderr`](https://nodejs.org/api/child_process.html#subprocessstderr) (as a stream).772- `'overlapped'`: Like `'pipe'` but asynchronous on Windows.773- `'ignore'`: Do not use `stderr`.774- `'inherit'`: Re-use the current process' `stderr`.775- an integer: Re-use a specific file descriptor from the current process.
21 unmodified lines
797798Type: `boolean`\799Default: `false`800801Add an `.all` property on the [promise](#all) and the [resolved value](#all-1). The property contains the output of the process with `stdout` and `stderr` [interleaved](#ensuring-all-output-is-interleaved).801Add an `.all` property on the [promise](#all) and the [resolved value](#all-1). The property contains the output of the subprocess with `stdout` and `stderr` [interleaved](#ensuring-all-output-is-interleaved).802803#### lines804805Type: `boolean`\806Default: `false`807808Split `stdout` and `stderr` into lines.809- [`result.stdout`](#stdout), [`result.stderr`](#stderr), [`result.all`](#all-1) and [`result.stdio`](#stdio) are arrays of lines.810- [`childProcess.stdout`](https://nodejs.org/api/child_process.html#subprocessstdout), [`childProcess.stderr`](https://nodejs.org/api/child_process.html#subprocessstderr), [`childProcess.all`](#all) and [`childProcess.stdio`](https://nodejs.org/api/child_process.html#subprocessstdio) iterate over lines instead of arbitrary chunks.810- [`subprocess.stdout`](https://nodejs.org/api/child_process.html#subprocessstdout), [`subprocess.stderr`](https://nodejs.org/api/child_process.html#subprocessstderr), [`subprocess.all`](#all) and [`subprocess.stdio`](https://nodejs.org/api/child_process.html#subprocessstdio) iterate over lines instead of arbitrary chunks.811- Any stream passed to the [`stdout`](#stdout-1), [`stderr`](#stderr-1) or [`stdio`](#stdio-1) option receives lines instead of arbitrary chunks.812813#### encoding814
20 unmodified lines
835836Type: `boolean`\837Default: `true` if the [`node`](#node) option is enabled, `false` otherwise838839Enables exchanging messages with the child process using [`childProcess.send(value)`](https://nodejs.org/api/child_process.html#subprocesssendmessage-sendhandle-options-callback) and [`childProcess.on('message', (value) => {})`](https://nodejs.org/api/child_process.html#event-message).839Enables exchanging messages with the subprocess using [`subprocess.send(value)`](https://nodejs.org/api/child_process.html#subprocesssendmessage-sendhandle-options-callback) and [`subprocess.on('message', (value) => {})`](https://nodejs.org/api/child_process.html#event-message).840841#### serialization842843Type: `string`\844Default: `'json'`845846Specify the kind of serialization used for sending messages between processes when using the [`ipc`](#ipc) option:846Specify the kind of serialization used for sending messages between subprocesses when using the [`ipc`](#ipc) option:847 - `json`: Uses `JSON.stringify()` and `JSON.parse()`.848 - `advanced`: Uses [`v8.serialize()`](https://nodejs.org/api/v8.html#v8_v8_serialize_value)849850[More info.](https://nodejs.org/api/child_process.html#child_process_advanced_serialization)
2 unmodified lines
853854Type: `boolean`\855Default: `false`856857Prepare child to run independently of its parent process. Specific behavior [depends on the platform](https://nodejs.org/api/child_process.html#child_process_options_detached).857Prepare subprocess to run independently of the current process. Specific behavior [depends on the platform](https://nodejs.org/api/child_process.html#child_process_options_detached).858859#### cleanup860861Type: `boolean`\862Default: `true`863864Kill the spawned process when the parent process exits unless either:865 - the spawned process is [`detached`](https://nodejs.org/api/child_process.html#child_process_options_detached)866 - the parent process is terminated abruptly, for example, with `SIGKILL` as opposed to `SIGTERM` or a normal exit864Kill the subprocess when the current process exits unless either:865 - the subprocess is [`detached`](https://nodejs.org/api/child_process.html#child_process_options_detached)866 - the current process is terminated abruptly, for example, with `SIGKILL` as opposed to `SIGTERM` or a normal exit867868#### timeout869870Type: `number`\871Default: `0`872873If `timeout` is greater than `0`, the child process will be [terminated](#killsignal) if it runs for longer than that amount of milliseconds.873If `timeout` is greater than `0`, the subprocess will be [terminated](#killsignal) if it runs for longer than that amount of milliseconds.874875#### cancelSignal876877Type: [`AbortSignal`](https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal)878879You can abort the spawned process using [`AbortController`](https://developer.mozilla.org/en-US/docs/Web/API/AbortController).879You can abort the subprocess using [`AbortController`](https://developer.mozilla.org/en-US/docs/Web/API/AbortController).880881When `AbortController.abort()` is called, [`.isCanceled`](#iscanceled) becomes `true`.882883#### forceKillAfterDelay884885Type: `number | false`\886Default: `5000`887888If the child process is terminated but does not exit, forcefully exit it by sending [`SIGKILL`](https://en.wikipedia.org/wiki/Signal_(IPC)#SIGKILL).888If the subprocess is terminated but does not exit, forcefully exit it by sending [`SIGKILL`](https://en.wikipedia.org/wiki/Signal_(IPC)#SIGKILL).889890The grace period is 5 seconds by default. This feature can be disabled with `false`.891892This works when the child process is terminated by either:892This works when the subprocess is terminated by either:893- the [`cancelSignal`](#cancelsignal), [`timeout`](#timeout), [`maxBuffer`](#maxbuffer) or [`cleanup`](#cleanup) option894- calling [`subprocess.kill()`](https://nodejs.org/api/child_process.html#subprocesskillsignal) with no arguments895896This does not work when the child process is terminated by either:896This does not work when the subprocess is terminated by either:897- calling [`subprocess.kill()`](https://nodejs.org/api/child_process.html#subprocesskillsignal) with an argument898- calling [`process.kill(subprocess.pid)`](https://nodejs.org/api/process.html#processkillpid-signal)899- sending a termination signal from another process900901Also, this does not work on Windows, because Windows [doesn't support signals](https://nodejs.org/api/process.html#process_signal_events): `SIGKILL` and `SIGTERM` both terminate the process immediately. Other packages (such as [`taskkill`](https://github.com/sindresorhus/taskkill)) can be used to achieve fail-safe termination on Windows.901Also, this does not work on Windows, because Windows [doesn't support signals](https://nodejs.org/api/process.html#process_signal_events): `SIGKILL` and `SIGTERM` both terminate the subprocess immediately. Other packages (such as [`taskkill`](https://github.com/sindresorhus/taskkill)) can be used to achieve fail-safe termination on Windows.902903#### killSignal904905Type: `string | number`\906Default: `SIGTERM`907908Signal used to terminate the child process when:908Signal used to terminate the subprocess when:909- using the [`cancelSignal`](#cancelsignal), [`timeout`](#timeout), [`maxBuffer`](#maxbuffer) or [`cleanup`](#cleanup) option910- calling [`subprocess.kill()`](https://nodejs.org/api/child_process.html#subprocesskillsignal) with no arguments911912This can be either a name (like `"SIGTERM"`) or a number (like `9`).
1 unmodified line
914#### argv0915916Type: `string`917918Explicitly set the value of `argv[0]` sent to the child process. This will be set to `file` if not specified.918Explicitly set the value of `argv[0]` sent to the subprocess. This will be set to `file` if not specified.919920#### uid921922Type: `number`923924Sets the user identity of the process.924Sets the user identity of the subprocess.925926#### gid927928Type: `number`929930Sets the group identity of the process.930Sets the group identity of the subprocess.931932#### windowsVerbatimArguments933934Type: `boolean`\
19 unmodified lines
954const {stdout} = await execa('npm', ['install'], {stdout: ['inherit', './output.txt', 'pipe']});955console.log(stdout);956```957958When combining `inherit` with other values, please note that the child process will not be an interactive TTY, even if the parent process is one.958When combining `inherit` with other values, please note that the subprocess will not be an interactive TTY, even if the current process is one.959960### Redirect a Node.js stream from/to stdin/stdout/stderr961962When passing a Node.js stream to the [`stdin`](#stdin), [`stdout`](#stdout-1) or [`stderr`](#stderr-1) option, Node.js requires that stream to have an underlying file or socket, such as the streams created by the `fs`, `net` or `http` core modules. Otherwise the following error is thrown.
25 unmodified lines
988989console.log(await pRetry(run, {retries: 5}));990```991992### Cancelling a spawned process992### Cancelling a subprocess993994```js995import {execa} from 'execa';996
26 unmodified lines
1023### Ensuring `all` output is interleaved10241025The `all` [stream](#all) and [string/`Uint8Array`](#all-1) properties are guaranteed to interleave [`stdout`](#stdout) and [`stderr`](#stderr).10261027However, for performance reasons, the child process might buffer and merge multiple simultaneous writes to `stdout` or `stderr`. This prevents proper interleaving.1027However, for performance reasons, the subprocess might buffer and merge multiple simultaneous writes to `stdout` or `stderr`. This prevents proper interleaving.10281029For example, this prints `1 3 2` instead of `1 2 3` because both `console.log()` are merged into a single write.10301031```js
33 unmodified lines