Skip to content
Myr

Add user guides (#989)

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

authored by ehmicky · committed by GitHub · parent fdd8a9f · Browse files · 32 files+3053 added−1582 removed
This commit

State

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

Diff stats

32 files+3053 added−1582 removed

  • tests:+1 added−1 removed
  • other:+3052 added−1581 removed

32 files+3053 added−1582 removed

added:docs/bash.md+864 added
1<picture>2 <source media="(prefers-color-scheme: dark)" srcset="../media/logo_dark.svg">3 <img alt="execa logo" src="../media/logo.svg" width="400">4</picture>5<br>67# 🔍 Differences with Bash and zx89This page describes the differences between [Bash](https://en.wikipedia.org/wiki/Bash_(Unix_shell)), Execa, and [zx](https://github.com/google/zx) (which inspired this feature). Execa intends to be more:10- [Performant](#performance)11- [Cross-platform](#shell): [no shell](shell.md) is used, only JavaScript.12- [Secure](#escaping): no shell injection.13- [Simple](#simplicity): minimalistic API, no [globals](#global-variables), no [binary](#main-binary), no [builtin CLI utilities](#builtin-utilities).14- [Featureful](#simplicity): all Execa features are available ([text lines iteration](#iterate-over-output-lines), [subprocess piping](#piping-stdout-to-another-command), [IPC](#ipc), [transforms](#transforms), [background subprocesses](#background-subprocess), [cancelation](#cancelation), [local binaries](#local-binaries), [cleanup on exit](termination.md#current-process-exit), [interleaved output](#interleaved-output), [forceful termination](termination.md#forceful-termination), and [more](../readme.md#documentation)).15- [Easy to debug](#debugging): [verbose mode](#verbose-mode), [detailed errors](#errors), [messages and stack traces](#cancelation), stateless API.1617## Flexibility1819Unlike shell languages like Bash, libraries like Execa and zx enable you to write scripts with a more featureful programming language (JavaScript). This allows complex logic (such as [parallel execution](#parallel-commands)) to be expressed easily. This also lets you use [any Node.js package](#builtin-utilities).2021## Shell2223The main difference between Execa and zx is that Execa does not require any shell. Shell-specific keywords and features are [written in JavaScript](#variable-substitution) instead.2425This is more cross-platform. For example, your code works the same on Windows machines without Bash installed.2627Also, there is no shell syntax to remember: everything is just plain JavaScript.2829If you really need a shell though, the [`shell`](shell.md) option can be used.3031## Simplicity3233Execa's scripting API mostly consists of only two methods: [`` $`command` ``](shell.md) and [`$(options)`](execution.md#globalshared-options).3435[No special binary](#main-binary) is recommended, no [global variable](#global-variables) is injected: scripts are regular Node.js files.3637Execa 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-subprocess): [`pid`](#pid), [IPC](ipc.md), [`unref()`](https://nodejs.org/api/child_process.html#subprocessunref), [`detached`](environment.md#background-subprocess), [`uid`](windows.md#uid-and-gid), [`gid`](windows.md#uid-and-gid), [`cancelSignal`](termination.md#canceling), etc.3839## Modularity4041zx includes many builtin utilities: `fetch()`, `question()`, `sleep()`, `stdin()`, `retry()`, `spinner()`, `chalk`, `fs-extra`, `os`, `path`, `globby`, `yaml`, `minimist`, `which`, Markdown scripts, remote scripts.4243Execa does not include [any utility](#builtin-utilities): it focuses on being small and modular instead. Any Node.js package can be used in your scripts.4445## Performance4647Spawning a shell for every command comes at a performance cost, which Execa avoids.4849Also, [local binaries](#local-binaries) can be directly executed without using `npx`.5051## Debugging5253Subprocesses can be hard to debug, which is why Execa includes a [`verbose`](#verbose-mode) option.5455Also, 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)`](termination.md#error-message-and-stack-trace).5657Finally, unlike Bash and zx, which are stateful (options, current directory, etc.), Execa is [purely functional](#current-directory), which also helps with debugging.5859## Examples6061### Main binary6263```sh64# Bash65bash file.sh66```6768```js69// zx70zx file.js7172// or a shebang can be used:73// #!/usr/bin/env zx74```7576```js77// Execa scripts are just regular Node.js files78node file.js79```8081### Global variables8283```js84// zx85await $`echo example`;86```8788```js89// Execa90import {$} from 'execa';9192await $`echo example`;93```9495[More info.](execution.md)9697### Command execution9899```sh100# Bash101echo example102```103104```js105// zx106await $`echo example`;107```108109```js110// Execa111await $`echo example`;112```113114### Multiline commands115116```sh117# Bash118npm run build \119 --example-flag-one \120 --example-flag-two121```122123```js124// zx125await $`npm run build ${[126 '--example-flag-one',127 '--example-flag-two',128]}`;129```130131```js132// Execa133await $`npm run build134 --example-flag-one135 --example-flag-two`;136```137138[More info.](execution.md#multiple-lines)139140### Concatenation141142```sh143# Bash144tmpDirectory="/tmp"145mkdir "$tmpDirectory/filename"146```147148```js149// zx150const tmpDirectory = '/tmp'151await $`mkdir ${tmpDirectory}/filename`;152```153154```js155// Execa156const tmpDirectory = '/tmp'157await $`mkdir ${tmpDirectory}/filename`;158```159160[More info.](execution.md#concatenation)161162### Variable substitution163164```sh165# Bash166echo $LANG167```168169```js170// zx171await $`echo $LANG`;172```173174```js175// Execa176await $`echo ${process.env.LANG}`;177```178179[More info.](input.md#environment-variables)180181### Escaping182183```sh184# Bash185echo 'one two'186```187188```js189// zx190await $`echo ${'one two'}`;191```192193```js194// Execa195await $`echo ${'one two'}`;196```197198[More info.](escaping.md)199200### Escaping multiple arguments201202```sh203# Bash204echo 'one two' '$'205```206207```js208// zx209await $`echo ${['one two', '$']}`;210```211212```js213// Execa214await $`echo ${['one two', '$']}`;215```216217[More info.](execution.md#multiple-arguments)218219### Subcommands220221```sh222# Bash223echo "$(echo example)"224```225226```js227// zx228const example = await $`echo example`;229await $`echo ${example}`;230```231232```js233// Execa234const example = await $`echo example`;235await $`echo ${example}`;236```237238[More info.](execution.md#subcommands)239240### Serial commands241242```sh243# Bash244echo one && echo two245```246247```js248// zx249await $`echo one && echo two`;250```251252```js253// Execa254await $`echo one`;255await $`echo two`;256```257258### Parallel commands259260```sh261# Bash262echo one &263echo two &264```265266```js267// zx268await Promise.all([$`echo one`, $`echo two`]);269```270271```js272// Execa273await Promise.all([$`echo one`, $`echo two`]);274```275276### Global/shared options277278```sh279# Bash280options="timeout 5"281$options echo one282$options echo two283$options echo three284```285286```js287// zx288const timeout = '5s';289await $`echo one`.timeout(timeout);290await $`echo two`.timeout(timeout);291await $`echo three`.timeout(timeout);292```293294```js295// Execa296import {$ as $_} from 'execa';297298const $ = $_({timeout: 5000});299300await $`echo one`;301await $`echo two`;302await $`echo three`;303```304305[More info.](execution.md#globalshared-options)306307### Environment variables308309```sh310# Bash311EXAMPLE=1 example_command312```313314```js315// zx316$.env.EXAMPLE = '1';317await $`example_command`;318delete $.env.EXAMPLE;319```320321```js322// Execa323await $({env: {EXAMPLE: '1'}})`example_command`;324```325326[More info.](input.md#environment-variables)327328### Local binaries329330```sh331# Bash332npx tsc --version333```334335```js336// zx337await $`npx tsc --version`;338```339340```js341// Execa342await $`tsc --version`;343```344345[More info.](environment.md#local-binaries)346347### Builtin utilities348349```js350// zx351const content = await stdin();352```353354```js355// Execa356import getStdin from 'get-stdin';357358const content = await getStdin();359```360361### Printing to stdout362363```sh364# Bash365echo example366```367368```js369// zx370echo`example`;371```372373```js374// Execa375console.log('example');376```377378### Silent stderr379380```sh381# Bash382echo example 2> /dev/null383```384385```js386// zx387await $`echo example`.stdio('inherit', 'pipe', 'ignore');388```389390```js391// Execa does not print stdout/stderr by default392await $`echo example`;393```394395### Verbose mode396397```sh398# Bash399set -v400echo example401```402403```js404// zx >=8405await $`echo example`.verbose();406407// or:408$.verbose = true;409```410411```js412// Execa413await $({verbose: 'full'})`echo example`;414```415416Or:417418```419NODE_DEBUG=execa node file.js420```421422Which prints:423424```425[19:49:00.360] [0] $ echo example426example427[19:49:00.383] [0] √ (done in 23ms)428```429430[More info.](debugging.md#verbose-mode)431432### Piping stdout to another command433434```sh435# Bash436echo npm run build | sort | head -n2437```438439```js440// zx441await $`npm run build | sort | head -n2`;442```443444```js445// Execa446await $`npm run build`447 .pipe`sort`448 .pipe`head -n2`;449```450451[More info.](pipe.md)452453### Piping stdout and stderr to another command454455```sh456# Bash457echo example |& cat458```459460```js461// zx462const echo = $`echo example`;463const cat = $`cat`;464echo.pipe(cat)465echo.stderr.pipe(cat.stdin);466await Promise.all([echo, cat]);467```468469```js470// Execa471await $({all: true})`echo example`472 .pipe({from: 'all'})`cat`;473```474475[More info.](pipe.md#source-file-descriptor)476477### Piping stdout to a file478479```sh480# Bash481echo example > output.txt482```483484```js485// zx486await $`echo example`.pipe(fs.createWriteStream('output.txt'));487```488489```js490// Execa491await $({stdout: {file: 'output.txt'}})`echo example`;492```493494[More info.](output.md#file-output)495496### Piping stdin from a file497498```sh499# Bash500echo example < input.txt501```502503```js504// zx505const cat = $`cat`;506fs.createReadStream('input.txt').pipe(cat.stdin);507await cat;508```509510```js511// Execa512await $({inputFile: 'input.txt'})`cat`;513```514515[More info.](input.md#file-input)516517### Iterate over output lines518519```sh520# Bash521while read522do523 if [[ "$REPLY" == *ERROR* ]]524 then525 echo "$REPLY"526 fi527done < <(npm run build)528```529530```js531// zx does not allow proper iteration.532// For example, the iteration does not handle subprocess errors.533```534535```js536// Execa537for await (const line of $`npm run build`) {538 if (line.includes('ERROR')) {539 console.log(line);540 }541}542```543544[More info.](lines.md#progressive-splitting)545546### Errors547548```sh549# Bash communicates errors only through the exit code and stderr550timeout 1 sleep 2551echo $?552```553554```js555// zx556const {557 stdout,558 stderr,559 exitCode,560 signal,561} = await $`sleep 2`.timeout('1s');562// file:///home/me/Desktop/node_modules/zx/build/core.js:146563// let output = new ProcessOutput(code, signal, stdout, stderr, combined, message);564// ^565// ProcessOutput [Error]:566// at file:///home/me/Desktop/example.js:2:20567// exit code: null568// signal: SIGTERM569// at ChildProcess.<anonymous> (file:///home/me/Desktop/node_modules/zx/build/core.js:146:26)570// at ChildProcess.emit (node:events:512:28)571// at maybeClose (node:internal/child_process:1098:16)572// at Socket.<anonymous> (node:internal/child_process:456:11)573// at Socket.emit (node:events:512:28)574// at Pipe.<anonymous> (node:net:316:12)575// at Pipe.callbackTrampoline (node:internal/async_hooks:130:17) {576// _code: null,577// _signal: 'SIGTERM',578// _stdout: '',579// _stderr: '',580// _combined: ''581// }582```583584```js585// Execa586const {587 stdout,588 stderr,589 exitCode,590 signal,591 signalDescription,592 originalMessage,593 shortMessage,594 command,595 escapedCommand,596 failed,597 timedOut,598 isCanceled,599 isTerminated,600 isMaxBuffer,601 // and other error-related properties: code, etc.602} = await $({timeout: 1})`sleep 2`;603// ExecaError: Command timed out after 1 milliseconds: sleep 2604// at file:///home/me/Desktop/example.js:2:20605// at ... {606// shortMessage: 'Command timed out after 1 milliseconds: sleep 2\nTimed out',607// originalMessage: '',608// command: 'sleep 2',609// escapedCommand: 'sleep 2',610// cwd: '/path/to/cwd',611// durationMs: 19.95693,612// failed: true,613// timedOut: true,614// isCanceled: false,615// isTerminated: true,616// isMaxBuffer: false,617// signal: 'SIGTERM',618// signalDescription: 'Termination',619// stdout: '',620// stderr: '',621// stdio: [undefined, '', ''],622// pipedFrom: []623// }624```625626[More info.](errors.md)627628### Exit codes629630```sh631# Bash632false633echo $?634```635636```js637// zx638const {exitCode} = await $`false`.nothrow();639echo`${exitCode}`;640```641642```js643// Execa644const {exitCode} = await $({reject: false})`false`;645console.log(exitCode);646```647648[More info.](errors.md#exit-code)649650### Timeouts651652```sh653# Bash654timeout 5 echo example655```656657```js658// zx659await $`echo example`.timeout('5s');660```661662```js663// Execa664await $({timeout: 5000})`echo example`;665```666667[More info.](termination.md#timeout)668669### Current filename670671```sh672# Bash673echo "$(basename "$0")"674```675676```js677// zx678await $`echo ${__filename}`;679```680681```js682// Execa683await $`echo ${import.meta.filename}`;684```685686### Current directory687688```sh689# Bash690cd project691```692693```js694// zx695cd('project');696697// or:698$.cwd = 'project';699```700701```js702// Execa703const $$ = $({cwd: 'project'});704```705706[More info.](environment.md#current-directory)707708### Multiple current directories709710```sh711# Bash712pushd project713pwd714popd715pwd716```717718```js719// zx720within(async () => {721 cd('project');722 await $`pwd`;723});724725await $`pwd`;726```727728```js729// Execa730await $({cwd: 'project'})`pwd`;731await $`pwd`;732```733734[More info.](environment.md#current-directory)735736### Background subprocess737738```sh739# Bash740echo one &741```742743```js744// zx does not allow setting the `detached` option745```746747```js748// Execa749await $({detached: true})`echo one`;750```751752[More info.](environment.md#background-subprocess)753754### IPC755756```sh757# Bash does not allow simple IPC758```759760```js761// zx does not allow simple IPC762```763764```js765// Execa766const subprocess = $({ipc: true})`node script.js`;767768subprocess.on('message', message => {769 if (message === 'ping') {770 subprocess.send('pong');771 }772});773```774775[More info.](ipc.md)776777### Transforms778779```sh780# Bash does not allow transforms781```782783```js784// zx does not allow transforms785```786787```js788// Execa789const transform = function * (line) {790 if (!line.includes('secret')) {791 yield line;792 }793};794795await $({stdout: [transform, 'inherit']})`echo ${'This is a secret.'}`;796```797798[More info.](transform.md)799800### Cancelation801802```sh803# Bash804kill $PID805```806807```js808// zx809subprocess.kill();810```811812```js813// Execa814// Can specify an error message and stack trace815subprocess.kill(error);816817// Or use an `AbortSignal`818const controller = new AbortController();819await $({signal: controller.signal})`node long-script.js`;820```821822[More info.](termination.md#canceling)823824### Interleaved output825826```sh827# Bash prints stdout and stderr interleaved828```829830```js831// zx separates stdout and stderr832const {stdout, stderr} = await $`node example.js`;833```834835```js836// Execa can interleave stdout and stderr837const {all} = await $({all: true})`node example.js`;838```839840[More info.](output.md#interleaved-output)841842### PID843844```sh845# Bash846echo example &847echo $!848```849850```js851// zx does not return `subprocess.pid`852```853854```js855// Execa856const {pid} = $`echo example`;857```858859[More info.](termination.md#inter-process-termination)860861<hr>862863[**Previous**: 📎 Windows](windows.md)\864[**Top**: Table of contents](../readme.md#documentation)
added:docs/binary.md+79 added
added:docs/debugging.md+105 added
1<picture>2 <source media="(prefers-color-scheme: dark)" srcset="../media/logo_dark.svg">3 <img alt="execa logo" src="../media/logo.svg" width="400">4</picture>5<br>67# 🐛 Debugging89## Command1011[`error.command`](../readme.md#resultcommand) contains the file and [arguments](input.md#command-arguments) that were run. It is intended for logging or debugging.1213[`error.escapedCommand`](../readme.md#resultescapedcommand) is the same, except control characters are escaped. This makes it safe to either print or copy and paste in a terminal, for debugging purposes.1415Since the escaping is fairly basic, neither `error.command` nor `error.escapedCommand` should be executed directly, including using [`execa()`](../readme.md#execafile-arguments-options) or [`execaCommand()`](../readme.md#execacommandcommand-options).1617```js18import {execa} from 'execa';1920try {21 await execa`npm run build\ntask`;22} catch (error) {23 console.error(error.command); // "npm run build\ntask"24 console.error(error.escapedCommand); // "npm run 'build\\ntask'"25 throw error;26}27```2829## Duration3031```js32try {33 const result = await execa`npm run build`;34 console.log('Command duration:', result.durationMs); // 15035} catch (error) {36 console.error('Command duration:', error.durationMs); // 15037 throw error;38}39```4041## Verbose mode4243### Short mode4445When the [`verbose`](../readme.md#optionsverbose) option is `'short'`, the [command](#command), [duration](#duration) and [error messages](errors.md#error-message) are printed on [`stderr`](https://en.wikipedia.org/wiki/Standard_streams#Standard_error_(stderr)).4647```js48// build.js49await execa({verbose: 'short'})`npm run build`;50```5152```sh53$ node build.js54[20:36:11.043] [0] $ npm run build55[20:36:11.885] [0] ✔ (done in 842ms)56```5758### Full mode5960When the [`verbose`](../readme.md#optionsverbose) option is `'full'`, the subprocess' [`stdout` and `stderr`](output.md) are also logged. Both are printed on [`stderr`](https://en.wikipedia.org/wiki/Standard_streams#Standard_error_(stderr)).6162The output is not logged if either:63- The [`stdout`](../readme.md#optionsstdout)/[`stderr`](../readme.md#optionsstderr) option is [`'ignore'`](output.md#ignore-output) or [`'inherit'`](output.md#terminal-output).64- The `stdout`/`stderr` is redirected to [a stream](streams.md#output), [a file](output.md#file-output), [a file descriptor](output.md#terminal-output), or [another subprocess](pipe.md).65- The [`encoding`](../readme.md#optionsencoding) option is [binary](binary.md#binary-output).6667```js68// build.js69await execa({verbose: 'full'})`npm run build`;70```7172```sh73$ node build.js74[20:36:11.043] [0] $ npm run build75Building application...76Done building.77[20:36:11.885] [0] ✔ (done in 842ms)78```7980### Global mode8182When the `NODE_DEBUG=execa` [environment variable](https://en.wikipedia.org/wiki/Environment_variable) is set, the [`verbose`](../readme.md#optionsverbose) option defaults to `'full'` for all commands.8384```js85// build.js8687// This is logged by default88await execa`npm run build`;89// This is not logged90await execa({verbose: 'none'})`npm run test`;91```9293```sh94$ NODE_DEBUG=execa node build.js95[20:36:11.043] [0] $ npm run build96Building application...97Done building.98[20:36:11.885] [0] ✔ (done in 842ms)99```100101<hr>102103[**Next**: 📎 Windows](windows.md)\104[**Previous**: 📞 Inter-process communication](ipc.md)\105[**Top**: Table of contents](../readme.md#documentation)
added:docs/environment.md+75 added
added:docs/errors.md+121 added
1<picture>2 <source media="(prefers-color-scheme: dark)" srcset="../media/logo_dark.svg">3 <img alt="execa logo" src="../media/logo.svg" width="400">4</picture>5<br>67# ❌ Errors89## Subprocess failure1011When the subprocess fails, the promise returned by [`execa()`](../readme.md#execafile-arguments-options) is rejected with an [`ExecaError`](../readme.md#execaerror) instance. The `error` has the same shape as successful [results](../readme.md#result), with a few additional [error-specific fields](../readme.md#execaerror). [`error.failed`](../readme.md#resultfailed) is always `true`.1213```js14import {execa, ExecaError} from 'execa';1516try {17 const result = await execa`npm run build`;18 console.log(result.failed); // false19} catch (error) {20 if (error instanceof ExecaError) {21 console.error(error.failed); // true22 }23}24```2526## Preventing exceptions2728When the [`reject`](../readme.md#optionsreject) option is `false`, the `error` is returned instead.2930```js31const resultOrError = await execa`npm run build`;32if (resultOrError.failed) {33 console.error(resultOrError);34}35```3637## Exit code3839The subprocess fails when its [exit code](https://en.wikipedia.org/wiki/Exit_status) is not `0`. The exit code is available as [`error.exitCode`](../readme.md#resultexitcode). It is `undefined` when the subprocess fails to spawn or when it was [terminated by a signal](termination.md#signal-termination).4041```js42try {43 await execa`npm run build`;44} catch (error) {45 // Either non-0 integer or undefined46 console.error(error.exitCode);47}48```4950## Failure reason5152The subprocess can fail for other reasons. Some of them can be detected using a specific boolean property:53- [`error.timedOut`](../readme.md#resulttimedout): [`timeout`](termination.md#timeout) option.54- [`error.isCanceled`](../readme.md#resultiscanceled): [`cancelSignal`](termination.md#canceling) option.55- [`error.isMaxBuffer`](../readme.md#resultismaxbuffer): [`maxBuffer`](output.md#big-output) option.56- [`error.isTerminated`](../readme.md#resultisterminated): [signal termination](termination.md#signal-termination). This includes the [`timeout`](termination.md#timeout) and [`cancelSignal`](termination.md#canceling) options since those terminate the subprocess with a [signal](termination.md#default-signal). However, this does not include the [`maxBuffer`](output.md#big-output) option.5758Otherwise, the subprocess failed because either:59- An exception was thrown in a [stream](streams.md) or [transform](transform.md).60- The command's executable file was not found.61- An invalid [option](../readme.md#options) was passed.62- There was not enough memory or too many subprocesses.6364```js65try {66 await execa`npm run build`;67} catch (error) {68 if (error.timedOut) {69 handleTimeout(error);70 }7172 throw error;73}74```7576## Error message7778For better [debugging](debugging.md), [`error.message`](../readme.md#errormessage) includes both:79- The command and the [reason it failed](#failure-reason).80- Its [`stdout`, `stderr`](output.md#stdout-and-stderr) and [other file descriptors'](output.md#additional-file-descriptors) output, separated with newlines and not [interleaved](output.md#interleaved-output).8182[`error.shortMessage`](../readme.md#errorshortmessage) is the same but without `stdout`/`stderr`.8384[`error.originalMessage`](../readme.md#errororiginalmessage) is the same but also without the command. This exists only in specific instances, such as when calling [`subprocess.kill(error)`](termination.md#error-message-and-stack-trace), using the [`cancelSignal`](termination.md#canceling) option, passing an invalid command or [option](../readme.md#options), or throwing an exception in a [stream](streams.md) or [transform](transform.md).8586```js87try {88 await execa`npm run build`;89} catch (error) {90 console.error(error.originalMessage);91 // The task "build" does not exist.9293 console.error(error.shortMessage);94 // Command failed with exit code 3: npm run build95 // The task "build" does not exist.9697 console.error(error.message);98 // Command failed with exit code 3: npm run build99 // The task "build" does not exist.100 // [stderr contents...]101 // [stdout contents...]102}103```104105## Retry on error106107Safely handle failures by using automatic retries and exponential backoff with the [`p-retry`](https://github.com/sindresorhus/p-retry) package.108109```js110import pRetry from 'p-retry';111import {execa} from 'execa';112113const run = () => execa`curl -sSL https://sindresorhus.com/unicorn`;114console.log(await pRetry(run, {retries: 5}));115```116117<hr>118119[**Next**: 🏁 Termination](termination.md)\120[**Previous**: 🌐 Environment](environment.md)\121[**Top**: Table of contents](../readme.md#documentation)
added:docs/escaping.md+87 added
1<picture>2 <source media="(prefers-color-scheme: dark)" srcset="../media/logo_dark.svg">3 <img alt="execa logo" src="../media/logo.svg" width="400">4</picture>5<br>67# 💬 Escaping/quoting89## Array syntax1011When using the [array syntax](execution.md#array-syntax), arguments are automatically escaped. They can contain any character, including spaces, tabs and newlines. However, they cannot contain [null bytes](https://en.wikipedia.org/wiki/Null_character): [binary inputs](binary.md#binary-input) should be used instead.1213```js14import {execa} from 'execa';1516await execa('npm', ['run', 'task with space']);17```1819## Template string syntax2021The same applies when using the [template string syntax](execution.md#template-string-syntax). However, spaces, tabs and newlines must use `${}`.2223```js24await execa`npm run ${'task with space'}`;25```2627## User-defined input2829The above syntaxes allow the file and its arguments to be user-defined by passing a variable.3031```js32const command = 'npm';33const commandArguments = ['run', 'task with space'];3435await execa(command, commandArguments);36await execa`${command} ${commandArguments}`;37```3839However, [`execaCommand()`](../readme.md#execacommandcommand-options) must be used instead if:40- _Both_ the file and its arguments are user-defined41- _And_ those are supplied as a single string4243This is only intended for very specific cases, such as a [REPL](https://en.wikipedia.org/wiki/Read%E2%80%93eval%E2%80%93print_loop). This should be avoided otherwise.4445```js46for await (const commandAndArguments of getReplLine()) {47 await execaCommand(commandAndArguments);48}49```5051Arguments passed to `execaCommand()` are automatically escaped. They can contain any character (except [null bytes](https://en.wikipedia.org/wiki/Null_character)), but spaces must be escaped with a backslash.5253```js54await execaCommand('npm run task\\ with\\ space');55```5657## Shells5859[Shells](shell.md) ([Bash](https://en.wikipedia.org/wiki/Bash_(Unix_shell)), [cmd.exe](https://en.wikipedia.org/wiki/Cmd.exe), etc.) are not used unless the [`shell`](../readme.md#optionsshell) option is set. This means shell-specific characters and expressions (`$variable`, `&&`, `||`, `;`, `|`, etc.) have no special meaning and do not need to be escaped.6061If you do set the `shell` option, arguments will not be automatically escaped anymore. Instead, they will be concatenated as a single string using spaces as delimiters.6263```js64await execa({shell: true})`npm ${'run'} ${'task with space'}`;65// Is the same as:66await execa({shell: true})`npm run task with space`;67```6869Therefore, you need to manually quote the arguments, using the shell-specific syntax.7071```js72await execa({shell: true})`npm ${'run'} ${'"task with space"'}`;73// Is the same as:74await execa({shell: true})`npm run "task with space"`;75```7677Sometimes a shell command is passed as argument to an executable that runs it indirectly. In that case, that shell command must quote its own arguments.7879```js80$`ssh host ${'npm run "task with space"'}`;81```8283<hr>8485[**Next**: 💻 Shell](shell.md)\86[**Previous**: ️▶️ Basic execution](execution.md)\87[**Top**: Table of contents](../readme.md#documentation)
added:docs/execution.md+137 added
1<picture>2 <source media="(prefers-color-scheme: dark)" srcset="../media/logo_dark.svg">3 <img alt="execa logo" src="../media/logo.svg" width="400">4</picture>5<br>67# ▶️ Basic execution89## Array syntax1011```js12import {execa} from 'execa';1314await execa('npm', ['run', 'build']);15```1617## Template string syntax1819All [available methods](../readme.md#methods) can use either the [array syntax](#array-syntax) or the template string syntax, which are equivalent.2021```js22await execa`npm run build`;23```2425### String argument2627```js28await execa`npm run ${'task with space'}`;29```3031### Number argument3233```js34await execa`npm run build --concurrency ${2}`;35```3637### Subcommands3839```js40const result = await execa`get-concurrency`;4142// Uses `result.stdout`43await execa`npm run build --concurrency ${result}`;44```4546### Concatenation4748```js49const tmpDirectory = '/tmp';50await execa`mkdir ${tmpDirectory}/filename`;51```5253### Multiple arguments5455```js56const result = await execa`get-concurrency`;5758await execa`npm ${['run', 'build', '--concurrency', 2]}`;59```6061### Multiple lines6263```js64await execa`npm run build65 --concurrency 266 --fail-fast`;67```6869## Options7071[Options](../readme.md#options) can be passed to influence the execution's behavior.7273### Array syntax7475```js76await execa('npm', ['run', 'build'], {timeout: 5000});77```7879### Template string syntax8081```js82await execa({timeout: 5000})`npm run build`;83```8485### Global/shared options8687```js88const timedExeca = execa({timeout: 5000});8990await timedExeca('npm', ['run', 'build']);91await timedExeca`npm run test`;92```9394## Return value9596### Subprocess9798The subprocess is returned as soon as it is spawned. It is a [`child_process` instance](https://nodejs.org/api/child_process.html#child_process_class_childprocess) with [additional methods and properties](../readme.md#subprocess).99100```js101const subprocess = execa`npm run build`;102console.log(subprocess.pid);103```104105### Result106107The subprocess is also a `Promise` that resolves with the [`result`](../readme.md#result).108109```js110const {stdout} = await execa`npm run build`;111```112113### Synchronous execution114115[Every method](../readme.md#methods) can be called synchronously by appending `Sync` to the method's name. The [`result`](../readme.md#result) is returned without needing to `await`. The [`subprocess`](#subprocess) is not returned: its methods and properties are not available.116117```js118import {execaSync} from 'execa';119120const {stdout} = execaSync`npm run build`;121```122123Synchronous execution is generally discouraged as it holds the CPU and prevents parallelization. Also, the following features cannot be used:124- Streams: [`subprocess.stdin`](../readme.md#subprocessstdin), [`subprocess.stdout`](../readme.md#subprocessstdout), [`subprocess.stderr`](../readme.md#subprocessstderr), [`subprocess.readable()`](../readme.md#subprocessreadablereadableoptions), [`subprocess.writable()`](../readme.md#subprocesswritablewritableoptions), [`subprocess.duplex()`](../readme.md#subprocessduplexduplexoptions).125- The [`stdin`](../readme.md#optionsstdin), [`stdout`](../readme.md#optionsstdout), [`stderr`](../readme.md#optionsstderr) and [`stdio`](../readme.md#optionsstdio) options cannot be [`'overlapped'`](../readme.md#optionsstdout), an [async iterable](lines.md#progressive-splitting), an async [transform](transform.md), a [`Duplex`](transform.md#duplextransform-streams), nor a [web stream](streams.md#web-streams). Node.js streams can be passed but only if either they [have a file descriptor](streams.md#file-descriptors), or the [`input`](../readme.md#optionsinput) option is used.126- Signal termination: [`subprocess.kill()`](../readme.md#subprocesskillerror), [`subprocess.pid`](../readme.md#subprocesspid), [`cleanup`](../readme.md#optionscleanup) option, [`cancelSignal`](../readme.md#optionscancelsignal) option, [`forceKillAfterDelay`](../readme.md#optionsforcekillafterdelay) option.127- Piping multiple subprocesses: [`subprocess.pipe()`](../readme.md#subprocesspipefile-arguments-options).128- [`subprocess.iterable()`](lines.md#progressive-splitting).129- [`ipc`](../readme.md#optionsipc) and [`serialization`](../readme.md#optionsserialization) options.130- [`result.all`](../readme.md#resultall) is not interleaved.131- [`detached`](../readme.md#optionsdetached) option.132- The [`maxBuffer`](../readme.md#optionsmaxbuffer) option is always measured in bytes, not in characters, [lines](../readme.md#optionslines) nor [objects](transform.md#object-mode). Also, it ignores transforms and the [`encoding`](../readme.md#optionsencoding) option.133134<hr>135136[**Next**: 💬 Escaping/quoting](escaping.md)\137[**Top**: Table of contents](../readme.md#documentation)
added:docs/input.md+108 added
1<picture>2 <source media="(prefers-color-scheme: dark)" srcset="../media/logo_dark.svg">3 <img alt="execa logo" src="../media/logo.svg" width="400">4</picture>5<br>67# 🎹 Input89## Command arguments1011The simplest way to pass input to a subprocess is to use command arguments.1213```js14import {execa} from 'execa';1516const commandArgument = 'build';17await execa`node child.js ${commandArgument}`;18```1920If the subprocess is a Node.js file, those are available using [`process.argv`](https://nodejs.org/api/process.html#processargv).2122```js23// child.js24import process from 'node:process';2526const commandArgument = process.argv[2];27```2829## Environment variables3031Unlike [command arguments](#command-arguments), [environment variables](https://en.wikipedia.org/wiki/Environment_variable) have names. They are commonly used to configure applications.3233If the subprocess spawns its own subprocesses, they inherit environment variables. To isolate subprocesses from each other, either command arguments or [`stdin`](#string-input) should be preferred instead.3435```js36// Keep the current process' environment variables, and set `NO_COLOR`37await execa({env: {NO_COLOR: 'true'})`node child.js`;38// Discard the current process' environment variables, only pass `NO_COLOR`39await execa({env: {NO_COLOR: 'true'}, extendEnv: false)`node child.js`;40```4142If the subprocess is a Node.js file, environment variables are available using [`process.env`](https://nodejs.org/api/process.html#processenv).4344```js45// child.js46import process from 'node:process';4748console.log(process.env.NO_COLOR);49```5051## String input5253Alternatively, input can be provided to [`stdin`](https://en.wikipedia.org/wiki/Standard_streams#Standard_input_(stdin)). Unlike [command arguments](#command-arguments) and [environment variables](#environment-variables) which have [size](https://unix.stackexchange.com/questions/120642/what-defines-the-maximum-size-for-a-command-single-argument) [limits](https://stackoverflow.com/questions/1078031/what-is-the-maximum-size-of-a-linux-environment-variable-value), `stdin` works when the input is big. Also, the input can be redirected from the [terminal](#terminal-input), a [file](#file-input), another [subprocess](pipe.md) or a [stream](streams.md#manual-streaming). Finally, this is required when the input might contain [null bytes](https://en.wikipedia.org/wiki/Null_character), for example when it might be [binary](binary.md#binary-input).5455If the input is already available as a string, it can be passed directly to the [`input`](../readme.md#optionsinput) option.5657```js58await execa({input: 'stdinInput'})`npm run scaffold`;59```6061The [`stdin`](../readme.md#optionsstdin) option can also be used, although the string must be wrapped in two arrays for [syntax reasons](output.md#multiple-targets).6263```js64await execa({stdin: [['stdinInput']]})`npm run scaffold`;65```6667## Ignore input6869```js70const subprocess = execa({stdin: 'ignore'})`npm run scaffold`;71console.log(subprocess.stdin); // undefined72await subprocess;73```7475## File input7677```js78await execa({inputFile: './input.txt'})`npm run scaffold`;79// Or:80await execa({stdin: {file: './input.txt'}})`npm run scaffold`;81// Or:82await execa({stdin: new URL('file:///path/to/input.txt')})`npm run scaffold`;83```8485## Terminal input8687The parent process' input can be re-used in the subprocess by passing `'inherit'`. This is especially useful to receive interactive input in command line applications.8889```js90await execa({stdin: 'inherit'})`npm run scaffold`;91```9293## Additional file descriptors9495The [`stdio`](../readme.md#optionsstdio) option can be used to pass some input to any [file descriptor](https://en.wikipedia.org/wiki/File_descriptor), as opposed to only [`stdin`](../readme.md#optionsstdin).9697```js98// Pass input to the file descriptor number 399await execa({100 stdio: ['pipe', 'pipe', 'pipe', new Uint8Array([/* ... */])],101})`npm run build`;102```103104<hr>105106[**Next**: 📢 Output](output.md)\107[**Previous**: 🏁 Termination](termination.md)\108[**Top**: Table of contents](../readme.md#documentation)
added:docs/ipc.md+54 added
added:docs/lines.md+144 added
1<picture>2 <source media="(prefers-color-scheme: dark)" srcset="../media/logo_dark.svg">3 <img alt="execa logo" src="../media/logo.svg" width="400">4</picture>5<br>67# 📃 Text lines89## Simple splitting1011If the [`lines`](../readme.md#optionslines) option is `true`, the output is split into lines, as an array of strings.1213```js14import {execa} from 'execa';1516const lines = await execa({lines: true})`npm run build`;17console.log(lines.join('\n'));18```1920## Iteration2122### Progressive splitting2324The subprocess' return value is an [async iterable](../readme.md#subprocesssymbolasynciterator). It iterates over the output's lines while the subprocess is still running.2526```js27for await (const line of execa`npm run build`) {28 if (line.includes('ERROR')) {29 console.log(line);30 }31}32```3334Alternatively, [`subprocess.iterable()`](../readme.md#subprocessiterablereadableoptions) can be called to pass [iterable options](../readme.md#readableoptions).3536The iteration waits for the subprocess to end (even when using [`break`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/break) or [`return`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/return)). It throws if the subprocess [fails](../readme.md#result). This means you do not need to `await` the subprocess' [promise](execution.md#result).3738```js39for await (const line of execa`npm run build`.iterable())) {40 /* ... */41}42```4344### Stdout/stderr4546By default, the subprocess' [`stdout`](https://en.wikipedia.org/wiki/Standard_streams#Standard_output_(stdout)) is used. The [`from`](../readme.md#readableoptionsfrom) iterable option can select a different file descriptor, such as [`'stderr'`](https://en.wikipedia.org/wiki/Standard_streams#Standard_error_(stderr)), [`'all'`](output.md#interleaved-output) or [`'fd3'`](output.md#additional-file-descriptors).4748```js49for await (const stderrLine of execa`npm run build`.iterable({from: 'stderr'})) {50 /* ... */51}52```5354## Newlines5556### Final newline5758The final newline is stripped from the output's last line, unless the [`stripFinalNewline`](../readme.md#optionsstripfinalnewline) option is `false`.5960```js61const {stdout} = await execa({stripFinalNewline: false})`npm run build`;62console.log(stdout.endsWith('\n')); // true63```6465### Array of lines6667When using the [`lines`](#simple-splitting) option, newlines are stripped from each line, unless the [`stripFinalNewline`](../readme.md#optionsstripfinalnewline) option is `false`.6869```js70// Each line now ends with '\n'.71// The last `line` might or might not end with '\n', depending on the output.72const lines = await execa({lines: true, stripFinalNewline: false})`npm run build`;73console.log(lines.join(''));74```7576### Iterable7778When [iterating](#progressive-splitting) over lines, newlines are stripped from each line, unless the [`preserveNewlines`](../readme.md#readableoptionspreservenewlines) iterable option is `true`.7980This option can also be used with [streams produced](streams.md#converting-a-subprocess-to-a-stream) by [`subprocess.readable()`](../readme.md#subprocessreadablereadableoptions) or [`subprocess.duplex()`](../readme.md#subprocessduplexduplexoptions), providing the [`binary`](binary.md#streams) option is `false`.8182```js83// `line` now ends with '\n'.84// The last `line` might or might not end with '\n', depending on the output.85for await (const line of execa`npm run build`.iterable({preserveNewlines: true})) {86 /* ... */87}88```8990### Transforms9192When using [transforms](transform.md), newlines are stripped from each `line` argument, unless the [`preserveNewlines`](../readme.md#transformoptionspreservenewlines) transform option is `true`.9394```js95// `line` now ends with '\n'.96// The last `line` might or might not end with '\n', depending on the output.97const transform = function * (line) { /* ... */ };9899await execa({stdout: {transform, preserveNewlines: true}})`npm run build`;100```101102Each `yield` produces at least one line. Calling `yield` multiple times or calling `yield *` produces multiples lines.103104```js105const transform = function * (line) {106 yield 'Important note:';107 yield 'Read the comments below.';108109 // Or:110 yield * [111 'Important note:',112 'Read the comments below.',113 ];114115 // Is the same as:116 yield 'Important note:\nRead the comments below.\n';117118 yield line;119};120121await execa({stdout: transform})`npm run build`;122```123124However, if the [`preserveNewlines`](../readme.md#transformoptionspreservenewlines) transform option is `true`, multiple `yield`s produce a single line instead.125126```js127const transform = function * (line) {128 yield 'Important note: ';129 yield 'Read the comments below.\n';130131 // Is the same as:132 yield 'Important note: Read the comments below.\n';133134 yield line;135};136137await execa({stdout: {transform, preserveNewlines: true}})`npm run build`;138```139140<hr>141142[**Next**: 🤖 Binary data](binary.md)\143[**Previous**: 📢 Output](output.md)\144[**Top**: Table of contents](../readme.md#documentation)
added:docs/node.md+43 added
added:docs/output.md+171 added
1<picture>2 <source media="(prefers-color-scheme: dark)" srcset="../media/logo_dark.svg">3 <img alt="execa logo" src="../media/logo.svg" width="400">4</picture>5<br>67# 📢 Output89## Stdout and stderr1011The [`stdout`](../readme.md#optionsstdout) and [`stderr`](../readme.md#optionsstderr) options redirect the subprocess output. They default to `'pipe'`, which returns the output using [`result.stdout`](../readme.md#resultstdout) and [`result.stderr`](../readme.md#resultstderr).1213```js14import {execa} from 'execa';1516const {stdout, stderr} = await execa`npm run build`;17console.log(stdout);18console.log(stderr);19```2021## Ignore output2223```js24const {stdout, stderr} = await execa({stdout: 'ignore'})`npm run build`;25console.log(stdout); // undefined26console.log(stderr); // string with errors27```2829## File output3031```js32await execa({stdout: {file: './output.txt'}})`npm run build`;33// Or:34await execa({stdout: new URL('file:///path/to/output.txt')})`npm run build`;35```3637## Terminal output3839The parent process' output can be re-used in the subprocess by passing `'inherit'`. This is especially useful to print to the terminal in command line applications.4041```js42await execa({stdout: 'inherit', stderr: 'inherit'})`npm run build`;43```4445To redirect from/to a different [file descriptor](https://en.wikipedia.org/wiki/File_descriptor), pass its [number](https://en.wikipedia.org/wiki/Standard_streams) or [`process.stdout`](https://nodejs.org/api/process.html#processstdout)/[`process.stderr`](https://nodejs.org/api/process.html#processstderr).4647```js48// Print both stdout/stderr to the parent stdout49await execa({stdout: process.stdout, stderr: process.stdout})`npm run build`;50// Or:51await execa({stdout: 1, stderr: 1})`npm run build`;52```5354## Multiple targets5556The output can be redirected to multiple targets by setting the [`stdout`](../readme.md#optionsstdout) or [`stderr`](../readme.md#optionsstderr) option to an array of values. This also allows specifying multiple inputs with the [`stdin`](../readme.md#optionsstdin) option.5758The following example redirects `stdout` to both the [terminal](#terminal-output) and an `output.txt` [file](#file-output), while also retrieving its value [programmatically](#stdout-and-stderr).5960```js61const {stdout} = await execa({stdout: ['inherit', {file: './output.txt'}, 'pipe']})`npm run build`;62console.log(stdout);63```6465When combining [`'inherit'`](#terminal-output) with other values, please note that the subprocess will not be an interactive TTY, even if the current process is one.6667## Interleaved output6869If the [`all`](../readme.md#optionsall) option is `true`, [`stdout`](https://en.wikipedia.org/wiki/Standard_streams#Standard_output_(stdout)) and [`stderr`](https://en.wikipedia.org/wiki/Standard_streams#Standard_error_(stderr)) are combined:70- [`result.all`](../readme.md#resultall): [`result.stdout`](../readme.md#resultstdout) + [`result.stderr`](../readme.md#resultstderr)71- [`subprocess.all`](../readme.md#subprocessall): [`subprocess.stdout`](../readme.md#subprocessstdout) + [`subprocess.stderr`](../readme.md#subprocessstderr)7273`stdout` and `stderr` are guaranteed to interleave. However, for performance reasons, the subprocess might buffer and merge multiple simultaneous writes to `stdout` or `stderr`. This can prevent proper interleaving.7475For example, this prints `1 3 2` instead of `1 2 3` because both `console.log()` are merged into a single write.7677```js78const {all} = await execa({all: true})`node example.js`;79```8081```js82// example.js83console.log('1'); // writes to stdout84console.error('2'); // writes to stderr85console.log('3'); // writes to stdout86```8788This can be worked around by using `setTimeout()`.8990```js91import {setTimeout} from 'timers/promises';9293console.log('1');94console.error('2');95await setTimeout(0);96console.log('3');97```9899## Stdout/stderr-specific options100101Some options are related to the subprocess output: [`verbose`](../readme.md#optionsverbose), [`lines`](../readme.md#optionslines), [`stripFinalNewline`](../readme.md#optionsstripfinalnewline), [`buffer`](../readme.md#optionsbuffer), [`maxBuffer`](../readme.md#optionsmaxbuffer). By default, those options apply to all [file descriptors](https://en.wikipedia.org/wiki/File_descriptor) ([`stdout`](https://en.wikipedia.org/wiki/Standard_streams#Standard_output_(stdout)), [`stderr`](https://en.wikipedia.org/wiki/Standard_streams#Standard_error_(stderr)), and [others](#additional-file-descriptors)). A plain object can be passed instead to apply them to only `stdout`, `stderr`, [`fd3`](#additional-file-descriptors), etc.102103```js104// Same value for stdout and stderr105await execa({verbose: 'full'})`npm run build`;106107// Different values for stdout and stderr108await execa({verbose: {stdout: 'none', stderr: 'full'}})`npm run build`;109```110111## Additional file descriptors112113The [`stdio`](../readme.md#optionsstdio) option is an array combining [`stdin`](../readme.md#optionsstdin), [`stdout`](../readme.md#optionsstdout), [`stderr`](../readme.md#optionsstderr) and any other file descriptor. It is useful when using additional [file descriptors](https://en.wikipedia.org/wiki/File_descriptor) beyond the [standard ones](https://en.wikipedia.org/wiki/Standard_streams), either for [input](input.md#additional-file-descriptors) or output.114115[`result.stdio`](../readme.md#resultstdio) can be used to retrieve some output from any file descriptor, as opposed to only [`stdout`](../readme.md#optionsstdout) and [`stderr`](../readme.md#optionsstderr).116117```js118// Retrieve output from file descriptor number 3119const {stdio} = await execa({120 stdio: ['pipe', 'pipe', 'pipe', 'pipe'],121})`npm run build`;122console.log(stdio[3]);123```124125## Shortcut126127The [`stdio`](../readme.md#optionsstdio) option can also be a single value [`'pipe'`](#stdout-and-stderr), [`'overlapped'`](windows.md#asynchronous-io), [`'ignore'`](#ignore-output) or [`'inherit'`](#terminal-output). This is a shortcut for setting that same value with the [`stdin`](../readme.md#optionsstdin), [`stdout`](../readme.md#optionsstdout) and [`stderr`](../readme.md#optionsstderr) options.128129```js130await execa({stdio: 'ignore'})`npm run build`;131// Same as:132await execa({stdin: 'ignore', stdout: 'ignore', stderr: 'ignore'})`npm run build`;133```134135## Big output136137To prevent high memory consumption, a maximum output size can be set using the [`maxBuffer`](../readme.md#optionsmaxbuffer) option. It defaults to 100MB.138139When this threshold is hit, the subprocess fails and [`error.isMaxBuffer`](../readme.md#resultismaxbuffer) becomes `true`. The truncated output is still available using [`error.stdout`](../readme.md#resultstdout) and [`error.stderr`](../readme.md#resultstderr).140141This is measured:142- By default: in [characters](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/length).143- If the [`encoding`](binary.md#encoding) option is `'buffer'`: in bytes.144- If the [`lines`](lines.md#simple-splitting) option is `true`: in lines.145- If a [transform in object mode](transform.md#object-mode) is used: in objects.146147```js148try {149 await execa({maxBuffer: 1_000_000})`npm run build`;150} catch (error) {151 if (error.isMaxBuffer) {152 console.error('Error: output larger than 1MB.');153 console.error(error.stdout);154 console.error(error.stderr);155 }156157 throw error;158}159```160161## Low memory162163When the [`buffer`](../readme.md#optionsbuffer) option is `false`, [`result.stdout`](../readme.md#resultstdout), [`result.stderr`](../readme.md#resultstderr), [`result.all`](../readme.md#resultall) and [`result.stdio[*]`](../readme.md#resultstdio) properties are not set.164165This prevents high memory consumption when the output is big. However, the output must be either ignored, [redirected](#file-output) or [streamed](streams.md). If streamed, this should be done right away to avoid missing any data.166167<hr>168169[**Next**: 📃 Text lines](lines.md)\170[**Previous**: 🎹 Input](input.md)\171[**Top**: Table of contents](../readme.md#documentation)
added:docs/pipe.md+167 added
1<picture>2 <source media="(prefers-color-scheme: dark)" srcset="../media/logo_dark.svg">3 <img alt="execa logo" src="../media/logo.svg" width="400">4</picture>5<br>67# 🔀 Piping multiple subprocesses89## Array syntax1011A subprocess' [output](output.md) can be [piped](https://en.wikipedia.org/wiki/Pipeline_(Unix)) to another subprocess' [input](input.md). The syntax is the same as [`execa(file, arguments?, options?)`](execution.md#array-syntax).1213```js14import {execa} from 'execa';1516// Similar to `npm run build | head -n 2` in shells17const {stdout} = await execa('npm', ['run', 'build'])18 .pipe('head', ['-n', '2']);19```2021## Template string syntax2223```js24const {stdout} = await execa`npm run build`25 .pipe`head -n 2`;26```2728## Advanced syntax2930```js31const subprocess = execa`head -n 2`;32const {stdout} = await execa`npm run build`33 .pipe(subprocess);34```3536## Options3738[Options](../readme.md#options) can be passed to either the source or the destination subprocess. Some [pipe-specific options](../readme.md#pipeoptions) can also be set by the destination subprocess.3940```js41const {stdout} = await execa('npm', ['run', 'build'], subprocessOptions)42 .pipe('head', ['-n', '2'], subprocessOrPipeOptions);43```4445```js46const {stdout} = await execa(subprocessOptions)`npm run build`47 .pipe(subprocessOrPipeOptions)`head -n 2`;48```4950```js51const subprocess = execa(subprocessOptions)`head -n 2`;52const {stdout} = await execa(subprocessOptions)`npm run build`53 .pipe(subprocess, pipeOptions);54```5556## Result5758When both subprocesses succeed, the [`result`](../readme.md#result) of the destination subprocess is returned. The [`result`](../readme.md#result) of the source subprocess is available in a [`result.pipedFrom`](../readme.md#resultpipedfrom) array.5960```js61const destinationResult = await execa`npm run build`62 .pipe`head -n 2`;63console.log(destinationResult.stdout); // First 2 lines of `npm run build`6465const sourceResult = destinationResult.pipedFrom[0];66console.log(sourceResult.stdout); // Full output of `npm run build`67```6869## Errors7071When either subprocess fails, `subprocess.pipe()` is rejected with that subprocess' error. If the destination subprocess fails, [`error.pipedFrom`](../readme.md#resultpipedfrom) includes the source subprocess' result, which is useful for debugging.7273```js74try {75 await execa`npm run build`76 .pipe`head -n 2`;77} catch (error) {78 if (error.pipedFrom.length === 0) {79 // `npm run build` failure80 console.error(error);81 } else {82 // `head -n 2` failure83 console.error(error);84 // `npm run build` output85 console.error(error.pipedFrom[0].stdout);86 }8788 throw error;89}90```9192## Series of subprocesses9394```js95await execa`npm run build`96 .pipe`sort`97 .pipe`head -n 2`;98```99100## 1 source, multiple destinations101102```js103const subprocess = execa`npm run build`;104const [sortedResult, truncatedResult] = await Promise.all([105 subprocess.pipe`sort`,106 subprocess.pipe`head -n 2`,107]);108```109110## Multiple sources, 1 destination111112```js113const destination = execa`./log-remotely.js`;114await Promise.all([115 execa`npm run build`.pipe(destination),116 execa`npm run test`.pipe(destination),117]);118```119120## Source file descriptor121122By default, the source's [`stdout`](../readme.md#subprocessstdout) is used, but this can be changed using the [`from`](../readme.md#pipeoptionsfrom) piping option.123124```js125await execa`npm run build`126 .pipe({from: 'stderr'})`head -n 2`;127```128129## Destination file descriptor130131By default, the destination's [`stdin`](../readme.md#subprocessstdin) is used, but this can be changed using the [`to`](../readme.md#pipeoptionsto) piping option.132133```js134await execa`npm run build`135 .pipe({to: 'fd3'})`./log-remotely.js`;136```137138## Unpipe139140Piping can be stopped using the [`unpipeSignal`](../readme.md#pipeoptionsunpipesignal) piping option.141142The [`subprocess.pipe()`](../readme.md#subprocesspipefile-arguments-options) method will be rejected with a cancelation error. However, each subprocess will keep running.143144```js145const abortController = new AbortController();146147process.on('SIGUSR1', () => {148 abortController.abort();149});150151// If the process receives SIGUSR1, `npm run build` stopped being logged remotely.152// However, it keeps running successfully.153try {154 await execa`npm run build`155 .pipe({unpipeSignal: abortController.signal})`./log-remotely.js`;156} catch (error) {157 if (!abortController.signal.aborted) {158 throw error;159 }160}161```162163<hr>164165[**Next**: ⏳️ Streams](streams.md)\166[**Previous**: 🧙 Transforms](transform.md)\167[**Top**: Table of contents](../readme.md#documentation)
modified:docs/scripts.md+22 added-816 removed
1# Node.js scripts1<picture>2 <source media="(prefers-color-scheme: dark)" srcset="../media/logo_dark.svg">3 <img alt="execa logo" src="../media/logo.svg" width="400">4</picture>5<br>63With Execa, you can write scripts with Node.js instead of a shell language. [Compared to Bash and zx](#differences-with-bash-and-zx), this is more: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 ([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#optionscleanup), [interleaved output](#interleaved-output), [forceful termination](../readme.md#optionsforcekillafterdelay), etc.).9 - [easy to debug](#debugging): [verbose mode](#verbose-mode), [detailed errors](#errors), [messages and stack traces](#cancellation), stateless API.7# 📜 Scripts89## Script files1011[Scripts](https://en.wikipedia.org/wiki/Shell_script) are Node.js files executing a series of commands. While those used to be written with a shell language like [Bash](https://en.wikipedia.org/wiki/Bash_(Unix_shell)), libraries like Execa provide with a better, modern experience.1213Scripts use [`$`](../readme.md#file-arguments-options) instead of [`execa`](../readme.md#execafile-arguments-options). The only difference is that `$` includes script-friendly default options: [`stdin: 'inherit'`](input.md#terminal-input) and [`preferLocal: true`](environment.md#local-binaries).1415[More info about the difference between Execa, Bash and zx.](bash.md)1617```js18import {$} from 'execa';1920const {stdout: name} = await $`cat package.json`
8 unmodified lines
29 $`sleep 2`,30 $`sleep 3`,31]);3227const dirName = 'foo bar';28await $`mkdir /tmp/${dirName}`;33const directoryName = 'foo bar';34await $`mkdir /tmp/${directoryName}`;35```3637## Template string syntax3833The examples below use the [template string syntax](../readme.md#template-string-syntax). However, the other syntax using [an array of arguments](../readme.md#execafile-arguments-options) is also available as `$(file, arguments?, options?)`.39Just like [`execa`](../readme.md#execafile-arguments-options), [`$`](../readme.md#file-arguments-options) can use either the [template string syntax](execution.md#template-string-syntax) or the [array syntax](execution.md#array-syntax).4035Also, the template string syntax can be used outside of script files: `$` is not required to use that syntax. For example, `execa` can use it too.41Conversely, the template string syntax can be used outside of script files: `$` is not required to use that syntax. For example, `execa` [can use it too](execution.md#template-string-syntax).4237The only difference between `$` and `execa` is that the former includes [script-friendly default options](../readme.md#file-arguments-options).3843```js44import {execa, $} from 'execa';4546const branch = await execa`git branch --show-current`;47await $('dep', ['deploy', `--branch=${branch}`]);48```4946## Examples50<hr>5148### Main binary4950```sh51# Bash52bash file.sh53```5455```js56// zx57zx file.js5859// or a shebang can be used:60// #!/usr/bin/env zx61```6263```js64// Execa scripts are just regular Node.js files65node file.js66```6768### Global variables6970```js71// zx72await $`echo example`;73```7475```js76// Execa77import {$} from 'execa';7879await $`echo example`;80```8182### Command execution8384```sh85# Bash86echo example87```8889```js90// zx91await $`echo example`;92```9394```js95// Execa96await $`echo example`;97```9899### Multiline commands100101```sh102# Bash103npm run build \104 --example-flag-one \105 --example-flag-two106```107108```js109// zx110await $`npm run build ${[111 '--example-flag-one',112 '--example-flag-two',113]}`;114```115116```js117// Execa118await $`npm run build119 --example-flag-one120 --example-flag-two`121```122123### Concatenation124125```sh126# Bash127tmpDir="/tmp"128mkdir "$tmpDir/filename"129```130131```js132// zx133const tmpDir = '/tmp'134await $`mkdir ${tmpDir}/filename`;135```136137```js138// Execa139const tmpDir = '/tmp'140await $`mkdir ${tmpDir}/filename`;141```142143### Variable substitution144145```sh146# Bash147echo $LANG148```149150```js151// zx152await $`echo $LANG`;153```154155```js156// Execa157await $`echo ${process.env.LANG}`;158```159160### Escaping161162```sh163# Bash164echo 'one two'165```166167```js168// zx169await $`echo ${'one two'}`;170```171172```js173// Execa174await $`echo ${'one two'}`;175```176177### Escaping multiple arguments178179```sh180# Bash181echo 'one two' '$'182```183184```js185// zx186await $`echo ${['one two', '$']}`;187```188189```js190// Execa191await $`echo ${['one two', '$']}`;192```193194### Subcommands195196```sh197# Bash198echo "$(echo example)"199```200201```js202// zx203const example = await $`echo example`;204await $`echo ${example}`;205```206207```js208// Execa209const example = await $`echo example`;210await $`echo ${example}`;211```212213### Serial commands214215```sh216# Bash217echo one && echo two218```219220```js221// zx222await $`echo one && echo two`;223```224225```js226// Execa227await $`echo one`;228await $`echo two`;229```230231### Parallel commands232233```sh234# Bash235echo one &236echo two &237```238239```js240// zx241await Promise.all([$`echo one`, $`echo two`]);242```243244```js245// Execa246await Promise.all([$`echo one`, $`echo two`]);247```248249### Global/shared options250251```sh252# Bash253options="timeout 5"254$options echo one255$options echo two256$options echo three257```258259```js260// zx261const timeout = '5s';262await $`echo one`.timeout(timeout);263await $`echo two`.timeout(timeout);264await $`echo three`.timeout(timeout);265```266267```js268// Execa269import {$ as $_} from 'execa';270271const $ = $_({timeout: 5000});272273await $`echo one`;274await $`echo two`;275await $`echo three`;276```277278### Environment variables279280```sh281# Bash282EXAMPLE=1 example_command283```284285```js286// zx287$.env.EXAMPLE = '1';288await $`example_command`;289delete $.env.EXAMPLE;290```291292```js293// Execa294await $({env: {EXAMPLE: '1'}})`example_command`;295```296297### Local binaries298299```sh300# Bash301npx tsc --version302```303304```js305// zx306await $`npx tsc --version`;307```308309```js310// Execa311await $`tsc --version`;312```313314### Builtin utilities315316```js317// zx318const content = await stdin();319```320321```js322// Execa323import getStdin from 'get-stdin';324325const content = await getStdin();326```327328### Printing to stdout329330```sh331# Bash332echo example333```334335```js336// zx337echo`example`;338```339340```js341// Execa342console.log('example');343```344345### Silent stderr346347```sh348# Bash349echo example 2> /dev/null350```351352```js353// zx354await $`echo example`.stdio('inherit', 'pipe', 'ignore');355```356357```js358// Execa does not print stdout/stderr by default359await $`echo example`;360```361362### Verbose mode363364```sh365# Bash366set -v367echo example368```369370```js371// zx >=8372await $`echo example`.verbose();373374// or:375$.verbose = true;376```377378```js379// Execa380import {$ as $_} from 'execa';381382// `verbose: 'short'` is also available383const $ = $_({verbose: 'full'});384385await $`echo example`;386```387388Or:389390```391NODE_DEBUG=execa node file.js392```393394Which prints:395396```397[19:49:00.360] [0] $ echo example398example399[19:49:00.383] [0] √ (done in 23ms)400```401402### Piping stdout to another command403404```sh405# Bash406echo npm run build | sort | head -n2407```408409```js410// zx411await $`npm run build | sort | head -n2`;412```413414```js415// Execa416await $`npm run build`417 .pipe`sort`418 .pipe`head -n2`;419```420421### Piping stdout and stderr to another command422423```sh424# Bash425echo example |& cat426```427428```js429// zx430const echo = $`echo example`;431const cat = $`cat`;432echo.pipe(cat)433echo.stderr.pipe(cat.stdin);434await Promise.all([echo, cat]);435```436437```js438// Execa439await $({all: true})`echo example`440 .pipe({from: 'all'})`cat`;441```442443### Piping stdout to a file444445```sh446# Bash447echo example > file.txt448```449450```js451// zx452await $`echo example`.pipe(fs.createWriteStream('file.txt'));453```454455```js456// Execa457await $({stdout: {file: 'file.txt'}})`echo example`;458```459460### Piping stdin from a file461462```sh463# Bash464echo example < file.txt465```466467```js468// zx469const cat = $`cat`470fs.createReadStream('file.txt').pipe(cat.stdin)471await cat472```473474```js475// Execa476await $({inputFile: 'file.txt'})`cat`477```478479### Iterate over output lines480481```sh482# Bash483while read484do485 if [[ "$REPLY" == *ERROR* ]]486 then487 echo "$REPLY"488 fi489done < <(npm run build)490```491492```js493// zx does not allow proper iteration.494// For example, the iteration does not handle subprocess errors.495```496497```js498// Execa499for await (const line of $`npm run build`) {500 if (line.includes('ERROR')) {501 console.log(line);502 }503}504```505506### Errors507508```sh509# Bash communicates errors only through the exit code and stderr510timeout 1 sleep 2511echo $?512```513514```js515// zx516const {517 stdout,518 stderr,519 exitCode,520 signal,521} = await $`sleep 2`.timeout('1s');522// file:///home/me/Desktop/node_modules/zx/build/core.js:146523// let output = new ProcessOutput(code, signal, stdout, stderr, combined, message);524// ^525// ProcessOutput [Error]:526// at file:///home/me/Desktop/example.js:2:20527// exit code: null528// signal: SIGTERM529// at ChildProcess.<anonymous> (file:///home/me/Desktop/node_modules/zx/build/core.js:146:26)530// at ChildProcess.emit (node:events:512:28)531// at maybeClose (node:internal/child_process:1098:16)532// at Socket.<anonymous> (node:internal/child_process:456:11)533// at Socket.emit (node:events:512:28)534// at Pipe.<anonymous> (node:net:316:12)535// at Pipe.callbackTrampoline (node:internal/async_hooks:130:17) {536// _code: null,537// _signal: 'SIGTERM',538// _stdout: '',539// _stderr: '',540// _combined: ''541// }542```543544```js545// Execa546const {547 stdout,548 stderr,549 exitCode,550 signal,551 signalDescription,552 originalMessage,553 shortMessage,554 command,555 escapedCommand,556 failed,557 timedOut,558 isCanceled,559 isTerminated,560 isMaxBuffer,561 // and other error-related properties: code, etc.562} = await $({timeout: 1})`sleep 2`;563// ExecaError: Command timed out after 1 milliseconds: sleep 2564// at file:///home/me/Desktop/example.js:2:20565// at ... {566// shortMessage: 'Command timed out after 1 milliseconds: sleep 2\nTimed out',567// originalMessage: '',568// command: 'sleep 2',569// escapedCommand: 'sleep 2',570// cwd: '/path/to/cwd',571// durationMs: 19.95693,572// failed: true,573// timedOut: true,574// isCanceled: false,575// isTerminated: true,576// isMaxBuffer: false,577// signal: 'SIGTERM',578// signalDescription: 'Termination',579// stdout: '',580// stderr: '',581// stdio: [undefined, '', ''],582// pipedFrom: []583// }584```585586### Exit codes587588```sh589# Bash590false591echo $?592```593594```js595// zx596const {exitCode} = await $`false`.nothrow();597echo`${exitCode}`;598```599600```js601// Execa602const {exitCode} = await $({reject: false})`false`;603console.log(exitCode);604```605606### Timeouts607608```sh609# Bash610timeout 5 echo example611```612613```js614// zx615await $`echo example`.timeout('5s');616```617618```js619// Execa620await $({timeout: 5000})`echo example`;621```622623### Current filename624625```sh626# Bash627echo "$(basename "$0")"628```629630```js631// zx632await $`echo ${__filename}`;633```634635```js636// Execa637import {fileURLToPath} from 'node:url';638import path from 'node:path';639640const __filename = path.basename(fileURLToPath(import.meta.url));641642await $`echo ${__filename}`;643```644645### Current directory646647```sh648# Bash649cd project650```651652```js653// zx654cd('project');655656// or:657$.cwd = 'project';658```659660```js661// Execa662const $$ = $({cwd: 'project'});663```664665### Multiple current directories666667```sh668# Bash669pushd project670pwd671popd672pwd673```674675```js676// zx677within(async () => {678 cd('project');679 await $`pwd`;680});681682await $`pwd`;683```684685```js686// Execa687await $({cwd: 'project'})`pwd`;688await $`pwd`;689```690691### Background subprocesses692693```sh694# Bash695echo one &696```697698```js699// zx does not allow setting the `detached` option700```701702```js703// Execa704await $({detached: true})`echo one`;705```706707### IPC708709```sh710# Bash does not allow simple IPC711```712713```js714// zx does not allow simple IPC715```716717```js718// Execa719const subprocess = $({ipc: true})`node script.js`;720721subprocess.on('message', message => {722 if (message === 'ping') {723 subprocess.send('pong');724 }725});726```727728### Transforms729730```sh731# Bash does not allow transforms732```733734```js735// zx does not allow transforms736```737738```js739// Execa740const transform = function * (line) {741 if (!line.includes('secret')) {742 yield line;743 }744};745746await $({stdout: [transform, 'inherit']})`echo ${'This is a secret.'}`;747```748749### Cancellation750751```sh752# Bash753kill $PID754```755756```js757// zx758subprocess.kill();759```760761```js762// Execa763// Can specify an error message and stack trace764subprocess.kill(error);765766// Or use an `AbortSignal`767const controller = new AbortController();768await $({signal: controller.signal})`node long-script.js`;769```770771### Interleaved output772773```sh774# Bash prints stdout and stderr interleaved775```776777```js778// zx separates stdout and stderr779const {stdout, stderr} = await $`node example.js`;780```781782```js783// Execa can interleave stdout and stderr784const {all} = await $({all: true})`node example.js`;785```786787### PID788789```sh790# Bash791echo example &792echo $!793```794795```js796// zx does not return `subprocess.pid`797```798799```js800// Execa801const {pid} = $`echo example`;802```803804## Differences with Bash and zx805806This section describes the differences between Bash, Execa, and [zx](https://github.com/google/zx) (which inspired this feature).807808### Flexibility809810Unlike shell languages like Bash, libraries like Execa and zx enable you to write scripts with a more featureful programming language (JavaScript). This allows complex logic (such as [parallel execution](#parallel-commands)) to be expressed easily. This also lets you use [any Node.js package](#builtin-utilities).811812### Shell813814The main difference between Execa and zx is that Execa does not require any shell. Shell-specific keywords and features are [written in JavaScript](#variable-substitution) instead.815816This is more cross-platform. For example, your code works the same on Windows machines without Bash installed.817818Also, there is no shell syntax to remember: everything is just plain JavaScript.819820If you really need a shell though, the [`shell`](../readme.md#optionsshell) option can be used.821822### Simplicity823824Execa's scripting API mostly consists of only two methods: [`` $`command` ``](../readme.md#file-arguments-options) and [`$(options)`](../readme.md#execaoptions).825826[No special binary](#main-binary) is recommended, no [global variable](#global-variables) is injected: scripts are regular Node.js files.827828Execa 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](../readme.md#optionsipc), [`unref()`](https://nodejs.org/api/child_process.html#subprocessunref), [`detached`](../readme.md#optionsdetached), [`uid`](../readme.md#optionsuid), [`gid`](../readme.md#optionsgid), [`cancelSignal`](../readme.md#optionscancelsignal), etc.829830### Modularity831832zx includes many builtin utilities: `fetch()`, `question()`, `sleep()`, `stdin()`, `retry()`, `spinner()`, `chalk`, `fs-extra`, `os`, `path`, `globby`, `yaml`, `minimist`, `which`, Markdown scripts, remote scripts.833834Execa does not include [any utility](#builtin-utilities): it focuses on being small and modular instead. Any Node.js package can be used in your scripts.835836### Performance837838Spawning a shell for every command comes at a performance cost, which Execa avoids.839840Also, [local binaries](#local-binaries) can be directly executed without using `npx`.841842### Debugging843844Subprocesses can be hard to debug, which is why Execa includes a [`verbose`](#verbose-mode) option.845846Also, 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#subprocesskillerror).847848Finally, unlike Bash and zx, which are stateful (options, current directory, etc.), Execa is [purely functional](#current-directory), which also helps with debugging.52[**Next**: 🐢 Node.js files](node.md)\53[**Previous**: 💻 Shell](shell.md)\54[**Top**: Table of contents](../readme.md#documentation)
added:docs/shell.md+38 added
added:docs/streams.md+117 added
1<picture>2 <source media="(prefers-color-scheme: dark)" srcset="../media/logo_dark.svg">3 <img alt="execa logo" src="../media/logo.svg" width="400">4</picture>5<br>67# ⏳️ Streams89## Node.js streams1011### Input1213```js14import {createReadStream} from 'node:fs';15import {once} from 'node:events';16import {execa} from 'execa';1718const readable = createReadStream('./input.txt');19await once(readable, 'open');20await execa({stdin: readable})`npm run scaffold`;21```2223### Output2425```js26import {createWriteStream} from 'node:fs';27import {once} from 'node:events';28import {execa} from 'execa';2930const writable = createWriteStream('./output.txt');31await once(writable, 'open');32await execa({stdout: writable})`npm run build`;33```3435### File descriptors3637When passing a Node.js stream to the [`stdin`](../readme.md#optionsstdin), [`stdout`](../readme.md#optionsstdout) or [`stderr`](../readme.md#optionsstderr) option, that stream must have an underlying file or socket, such as the streams created by the [`fs`](https://nodejs.org/api/fs.html#filehandlecreatereadstreamoptions), [`net`](https://nodejs.org/api/net.html#new-netsocketoptions) or [`http`](https://nodejs.org/api/http.html#class-httpincomingmessage) core modules. Otherwise the following error is thrown.3839```40TypeError [ERR_INVALID_ARG_VALUE]: The argument 'stdio' is invalid.41```4243This limitation can be worked around by either:44- Using the [`input`](../readme.md#optionsinput) option instead of the [`stdin`](../readme.md#optionsstdin) option.45- Passing a [web stream](#web-streams).46- Passing [`[nodeStream, 'pipe']`](output.md#multiple-targets) instead of `nodeStream`.4748## Web streams4950[Web streams](https://nodejs.org/api/webstreams.html) ([`ReadableStream`](https://developer.mozilla.org/en-US/docs/Web/API/ReadableStream) or [`WritableStream`](https://developer.mozilla.org/en-US/docs/Web/API/WritableStream)) can be used instead of [Node.js streams](https://nodejs.org/api/stream.html).5152```js53const response = await fetch('https://example.com');54await execa({stdin: response.body})`npm run build`;55```5657## Iterables as input5859```js60const getReplInput = async function * () {61 for await (const replLine of getReplLines()) {62 yield replLine;63 }64};6566await execa({stdin: getReplInput()})`npm run scaffold`;67```6869## Manual streaming7071[`subprocess.stdin`](../readme.md#subprocessstdin) is a Node.js [`Readable`](https://nodejs.org/api/stream.html#class-streamreadable) stream and [`subprocess.stdout`](../readme.md#subprocessstdout)/[`subprocess.stderr`](../readme.md#subprocessstderr)/[`subprocess.all`](../readme.md#subprocessall) are Node.js [`Writable`](https://nodejs.org/api/stream.html#class-streamwritable) streams.7273They can be used to stream input/output manually. This is intended for advanced situations. In most cases, the following simpler solutions can be used instead:74- [`result.stdout`](output.md#stdout-and-stderr), [`result.stderr`](output.md#stdout-and-stderr) or [`result.stdio`](output.md#additional-file-descriptors).75- The [`stdin`](../readme.md#optionsstdin), [`stdout`](../readme.md#optionsstdout), [`stderr`](../readme.md#optionsstderr) or [`stdio`](../readme.md#optionsstdio) options.76- [`subprocess.iterable()`](lines.md#progressive-splitting).77- [`subprocess.pipe()`](pipe.md).7879## Converting a subprocess to a stream8081### Convert8283The [`subprocess.readable()`](../readme.md#subprocessreadablereadableoptions), [`subprocess.writable()`](../readme.md#subprocesswritablewritableoptions) and [`subprocess.duplex()`](../readme.md#subprocessduplexduplexoptions) methods convert the subprocess to a Node.js [`Readable`](https://nodejs.org/api/stream.html#class-streamreadable), [`Writable`](https://nodejs.org/api/stream.html#class-streamwritable) and [`Duplex`](https://nodejs.org/api/stream.html#class-streamduplex) stream.8485This is useful when using a library or API that expects Node.js streams as arguments. In every other situation, the simpler solutions described [above](#manual-streaming) can be used instead.8687```js88const readable = execa`npm run scaffold`.readable();8990const writable = execa`npm run scaffold`.writable();9192const duplex = execa`npm run scaffold`.duplex();93```9495### Different file descriptor9697By default, [`subprocess.readable()`](../readme.md#subprocessreadablereadableoptions), [`subprocess.writable()`](../readme.md#subprocesswritablewritableoptions) and [`subprocess.duplex()`](../readme.md#subprocessduplexduplexoptions) methods use [`stdin`](../readme.md#subprocessstdin) and [`stdout`](../readme.md#subprocessstdout). This can be changed using the [`from`](../readme.md#readableoptionsfrom) and [`to`](../readme.md#writableoptionsto) options.9899```js100const readable = execa`npm run scaffold`.readable({from: 'stderr'});101102const writable = execa`npm run scaffold`.writable({to: 'fd3'});103104const duplex = execa`npm run scaffold`.duplex({from: 'stderr', to: 'fd3'});105```106107### Error handling108109When using [`subprocess.readable()`](../readme.md#subprocessreadablereadableoptions), [`subprocess.writable()`](../readme.md#subprocesswritablewritableoptions) or [`subprocess.duplex()`](../readme.md#subprocessduplexduplexoptions), the stream waits for the subprocess to end, and emits an [`error`](https://nodejs.org/api/stream.html#event-error) event if the subprocess [fails](errors.md). This differs from [`subprocess.stdin`](../readme.md#subprocessstdin), [`subprocess.stdout`](../readme.md#subprocessstdout) and [`subprocess.stderr`](../readme.md#subprocessstderr)'s behavior.110111This means you do not need to `await` the subprocess' [promise](execution.md#result). On the other hand, you (or the library using the stream) do need to both consume the stream, and handle its `error` event. This can be done by using [`await finished(stream)`](https://nodejs.org/api/stream.html#streamfinishedstream-options), [`await pipeline(..., stream, ...)`](https://nodejs.org/api/stream.html#streampipelinesource-transforms-destination-options) or [`await text(stream)`](https://nodejs.org/api/webstreams.html#streamconsumerstextstream) which throw an exception when the stream errors.112113<hr>114115[**Next**: 📞 Inter-process communication](ipc.md)\116[**Previous**: 🔀 Piping multiple subprocesses](pipe.md)\117[**Top**: Table of contents](../readme.md#documentation)
added:docs/termination.md+185 added
1<picture>2 <source media="(prefers-color-scheme: dark)" srcset="../media/logo_dark.svg">3 <img alt="execa logo" src="../media/logo.svg" width="400">4</picture>5<br>67# 🏁 Termination89## Canceling1011The [`cancelSignal`](../readme.md#optionscancelsignal) option can be used to cancel a subprocess. When [`abortController`](https://developer.mozilla.org/en-US/docs/Web/API/AbortController) is [aborted](https://developer.mozilla.org/en-US/docs/Web/API/AbortController/abort), a [`SIGTERM` signal](#default-signal) is sent to the subprocess.1213```js14import {execa} from 'execa';1516const abortController = new AbortController();1718setTimeout(() => {19 abortController.abort();20}, 5000);2122try {23 await execa({cancelSignal: abortController.signal})`npm run build`;24} catch (error) {25 if (error.isCanceled) {26 console.error('Aborted by cancelSignal.');27 }2829 throw error;30}31```3233## Timeout3435If the subprocess lasts longer than the [`timeout`](../readme.md#optionstimeout) option, a [`SIGTERM` signal](#default-signal) is sent to it.3637```js38try {39 await execa({timeout: 5000})`npm run build`;40} catch (error) {41 if (error.timedOut) {42 console.error('Timed out.');43 }4445 throw error;46}47```4849## Current process exit5051If the current process exits, the subprocess is automatically [terminated](#default-signal) unless either:52- The [`cleanup`](../readme.md#optionscleanup) option is `false`.53- The subprocess is run in the background using the [`detached`](../readme.md#optionsdetached) option.54- The current process was terminated abruptly, for example, with [`SIGKILL`](#sigkill) as opposed to [`SIGTERM`](#sigterm) or a successful exit.5556## Signal termination5758[`subprocess.kill()`](../readme.md#subprocesskillsignal-error) sends a [signal](https://en.wikipedia.org/wiki/Signal_(IPC)) to the subprocess. This is an inter-process message handled by the OS. Most (but [not all](https://github.com/ehmicky/human-signals#action)) signals terminate the subprocess.5960[More info.](https://nodejs.org/api/child_process.html#subprocesskillsignal)6162### SIGTERM6364[`SIGTERM`](https://en.wikipedia.org/wiki/Signal_(IPC)#SIGTERM) is the default signal. It terminates the subprocess.6566```js67const subprocess = execa`npm run build`;68subprocess.kill();69// Is the same as:70subprocess.kill('SIGTERM');71```7273The subprocess can [handle that signal](https://nodejs.org/api/process.html#process_signal_events) to run some cleanup logic.7475```js76process.on('SIGTERM', () => {77 cleanup();78 process.exit(1);79})80```8182### SIGKILL8384[`SIGKILL`](https://en.wikipedia.org/wiki/Signal_(IPC)#SIGKILL) is like [`SIGTERM`](#sigterm) except it forcefully terminates the subprocess, i.e. it does not allow it to handle the signal.8586```js87subprocess.kill('SIGKILL');88```8990### Other signals9192Other signals can be passed as argument. However, most other signals do not fully [work on Windows](https://github.com/ehmicky/cross-platform-node-guide/blob/main/docs/6_networking_ipc/signals.md#cross-platform-signals).9394### Default signal9596The [`killSignal`](../readme.md#optionskillsignal) option sets the default signal used by [`subprocess.kill()`](../readme.md#subprocesskillsignal-error) and the following options: [`cancelSignal`](#canceling), [`timeout`](#timeout), [`maxBuffer`](output.md#big-output) and [`cleanup`](#current-process-exit). It is [`SIGTERM`](#sigterm) by default.9798```js99const subprocess = execa({killSignal: 'SIGKILL'})`npm run build`;100subprocess.kill(); // Forceful termination101```102103### Signal name and description104105When a subprocess was terminated by a signal, [`error.isTerminated`](../readme.md#resultisterminated) is `true`.106107Also, [`error.signal`](../readme.md#resultsignal) and [`error.signalDescription`](../readme.md#resultsignaldescription) indicate the signal's name and [human-friendly description](https://github.com/ehmicky/human-signals). On Windows, those are only set if the current process terminated the subprocess, as opposed to [another process](#inter-process-termination).108109```js110try {111 await execa`npm run build`;112} catch (error) {113 if (error.isTerminated) {114 console.error(error.signal); // SIGFPE115 console.error(error.signalDescription); // 'Floating point arithmetic error'116 }117118 throw error;119}120```121122## Forceful termination123124If the subprocess is terminated but does not exit, [`SIGKILL`](#sigkill) is automatically sent to forcefully terminate it.125126The grace period is set by the [`forceKillAfterDelay`](../readme.md#optionsforcekillafterdelay) option, which is 5 seconds by default. This feature can be disabled with `false`.127128This works when the subprocess is terminated by either:129- Calling [`subprocess.kill()`](../readme.md#subprocesskillsignal-error) with no arguments.130- The [`cancelSignal`](#canceling), [`timeout`](#timeout), [`maxBuffer`](output.md#big-output) or [`cleanup`](#current-process-exit) option.131132This does not work when the subprocess is terminated by either:133- Calling [`subprocess.kill()`](../readme.md#subprocesskillsignal-error) with a specific signal.134- Calling [`process.kill(subprocess.pid)`](../readme.md#subprocesspid).135- Sending a termination signal [from another process](#inter-process-termination).136137Also, 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.138139```js140// No forceful termination141const subprocess = execa({forceKillAfterDelay: false})`npm run build`;142subprocess.kill();143```144145## Inter-process termination146147[`subprocess.kill()`](../readme.md#subprocesskillsignal-error) only works when the current process terminates the subprocess. To terminate the subprocess from a different process (for example, a terminal), its [`subprocess.pid`](../readme.md#subprocesspid) can be used instead.148149```js150const subprocess = execa`npm run build`;151console.log('PID:', subprocess.pid); // PID: 6513152await subprocess;153```154155```sh156$ kill -SIGTERM 6513157```158159## Error message and stack trace160161When terminating a subprocess, it is possible to include an error message and stack trace by using [`subprocess.kill(error)`](../readme.md#subprocesskillerror). The `error` argument will be available at [`error.cause`](../readme.md#errorcause).162163```js164try {165 const subprocess = execa`npm run build`;166 setTimeout(() => {167 subprocess.kill(new Error('Timed out after 5 seconds.'));168 }, 5000);169 await subprocess;170} catch (error) {171 if (error.isTerminated) {172 console.error(error.cause); // new Error('Timed out after 5 seconds.')173 console.error(error.cause.stack); // Stack trace from `error.cause`174 console.error(error.originalMessage); // 'Timed out after 5 seconds.'175 }176177 throw error;178}179```180181<hr>182183[**Next**: 🎹 Input](input.md)\184[**Previous**: ❌ Errors](errors.md)\185[**Top**: Table of contents](../readme.md#documentation)
modified:docs/transform.md+42 added-164 removed
1# Transforms1<picture>2 <source media="(prefers-color-scheme: dark)" srcset="../media/logo_dark.svg">3 <img alt="execa logo" src="../media/logo.svg" width="400">4</picture>5<br>67# 🧙 Transforms89## Summary105Transforms map or filter the input or output of a subprocess. They are defined by passing a [generator function](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/function*) or a [transform options object](#transform-options) to the [`stdin`](../readme.md#optionsstdin), [`stdout`](../readme.md#optionsstdout), [`stderr`](../readme.md#optionsstderr) or [`stdio`](../readme.md#optionsstdio) option. It can be [`async`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function*).11Transforms map or filter the input or output of a subprocess. They are defined by passing a [generator function](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/function*) or a [transform options object](../readme.md#transform-options) to the [`stdin`](../readme.md#optionsstdin), [`stdout`](../readme.md#optionsstdout), [`stderr`](../readme.md#optionsstderr) or [`stdio`](../readme.md#optionsstdio) option. It can be [`async`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function*).1213```js14import {execa} from 'execa';15
1 unmodified line
17 const prefix = line.includes('error') ? 'ERROR' : 'INFO';18 yield `${prefix}: ${line}`;19};2015const {stdout} = await execa('./run.js', {stdout: transform});21const {stdout} = await execa({stdout: transform})`npm run build`;22console.log(stdout); // HELLO23```2419## Encoding25## Difference with iteration2621The `line` argument passed to the transform is a string by default.\22However, if the [`binary`](#transformoptionsbinary) transform option is `true` or if the [`encoding`](../readme.md#optionsencoding) subprocess option is binary, it is an `Uint8Array` instead.27Transforms operate one `line` at a time, just like [`subprocess.iterable()`](lines.md#progressive-splitting). However, unlike iteration, transforms:28- Modify the subprocess' [output](../readme.md#resultstdout) and [streams](../readme.md#subprocessstdout).29- Can apply to the subprocess' input.30- Are defined using a [generator function](#summary), [`Duplex`](#duplextransform-streams) stream, Node.js [`Transform`](#duplextransform-streams) stream or web [`TransformStream`](#duplextransform-streams).3124The transform can `yield` either a `string` or an `Uint8Array`, regardless of the `line` argument's type.2532## Filtering3334`yield` can be called 0, 1 or multiple times. Not calling `yield` enables filtering a specific line.3536```js31import {execa} from 'execa';3237const transform = function * (line) {38 if (!line.includes('secret')) {39 yield line;40 }41};4239const {stdout} = await execa('echo', ['This is a secret.'], {stdout: transform});43const {stdout} = await execa({stdout: transform})`echo ${'This is a secret'}`;44console.log(stdout); // ''45```4643## Binary data4445The transform iterates over lines by default.\46However, if the [`binary`](#transformoptionsbinary) transform option is `true` or if the [`encoding`](../readme.md#optionsencoding) subprocess option is binary, it iterates over arbitrary chunks of data instead.4748```js49await execa('./binary.js', {stdout: {transform, binary: true}});50```5152This is more efficient and recommended if the data is either:53- Binary: Which does not have lines.54- Text: But the transform works even if a line or word is split across multiple chunks.5556## Newlines5758Unless the [`binary`](#transformoptionsbinary) transform option is `true`, the transform iterates over lines.59By default, newlines are stripped from each `line` argument.6061```js62// `line`'s value never ends with '\n'.63const transform = function * (line) { /* ... */ };6465await execa('./run.js', {stdout: transform});66```6768However, if the [`preserveNewlines`](#transformoptionspreservenewlines) transform option is `true`, newlines are kept.6970```js71// `line`'s value ends with '\n'.72// The output's last `line` might or might not end with '\n', depending on the output.73const transform = function * (line) { /* ... */ };7475await execa('./run.js', {stdout: {transform, preserveNewlines: true}});76```7778Each `yield` produces at least one line. Calling `yield` multiple times or calling `yield *` produces multiples lines.7980```js81const transform = function * (line) {82 yield 'Important note:';83 yield 'Read the comments below.';8485 // Or:86 yield * [87 'Important note:',88 'Read the comments below.',89 ];9091 // Is the same as:92 yield 'Important note:\nRead the comments below.\n';9394 yield line95};9697await execa('./run.js', {stdout: transform});98```99100However, if the [`preserveNewlines`](#transformoptionspreservenewlines) transform option is `true`, multiple `yield`s produce a single line instead.101102```js103const transform = function * (line) {104 yield 'Important note: ';105 yield 'Read the comments below.\n';106107 // Is the same as:108 yield 'Important note: Read the comments below.\n';109110 yield line111};112113await execa('./run.js', {stdout: {transform, preserveNewlines: true}});114```11547## Object mode48118By default, `stdout` and `stderr`'s transforms must return a string or an `Uint8Array`.\119However, if the [`objectMode`](#transformoptionsobjectmode) transform option is `true`, any type can be returned instead, except `null` or `undefined`. The subprocess' [`result.stdout`](../readme.md#resultstdout)/[`result.stderr`](../readme.md#resultstderr) will be an array of values.49By default, [`stdout`](../readme.md#optionsstdout) and [`stderr`](../readme.md#optionsstderr)'s transforms must return a string or an `Uint8Array`. However, if the [`objectMode`](../readme.md#transformoptionsobjectmode) transform option is `true`, any type can be returned instead, except `null` or `undefined`. The subprocess' [`result.stdout`](../readme.md#resultstdout)/[`result.stderr`](../readme.md#resultstderr) will be an array of values.5051```js52const transform = function * (line) {53 yield JSON.parse(line);54};55126const {stdout} = await execa('./jsonlines-output.js', {stdout: {transform, objectMode: true}});56const {stdout} = await execa({stdout: {transform, objectMode: true}})`node jsonlines-output.js`;57for (const data of stdout) {128 console.log(stdout); // {...}58 console.log(stdout); // {...object}59}60```6162[`stdin`](../readme.md#optionsstdin) can also use `objectMode: true`.
3 unmodified lines
66 yield JSON.stringify(line);67};6869const input = [{event: 'example'}, {event: 'otherExample'}];140await execa('./jsonlines-input.js', {stdin: [input, {transform, objectMode: true}]});70await execa({stdin: [input, {transform, objectMode: true}]})`node jsonlines-input.js`;71```7273## Sharing state74145State can be shared between calls of the [`transform`](#transformoptionstransform) and [`final`](#transformoptionsfinal) functions.75State can be shared between calls of the [`transform`](../readme.md#transformoptionstransform) and [`final`](../readme.md#transformoptionsfinal) functions.7677```js148let count = 078let count = 0;7980// Prefix line number81const transform = function * (line) {82 yield `[${count++}] ${line}`;
1 unmodified line
84```8586## Finalizing87158To create additional lines after the last one, a [`final`](#transformoptionsfinal) generator function can be used.88To create additional lines after the last one, a [`final`](../readme.md#transformoptionsfinal) generator function can be used.8990```js91let count = 0;92
5 unmodified lines
98const final = function * () {99 yield `Number of lines: ${count}`;100};101172const {stdout} = await execa('./command.js', {stdout: {transform, final}});102const {stdout} = await execa({stdout: {transform, final}})`npm run build`;103console.log(stdout); // Ends with: 'Number of lines: 54'104```105106## Duplex/Transform streams107108A [`Duplex`](https://nodejs.org/api/stream.html#class-streamduplex) stream, Node.js [`Transform`](https://nodejs.org/api/stream.html#class-streamtransform) stream or web [`TransformStream`](https://developer.mozilla.org/en-US/docs/Web/API/TransformStream) can be used instead of a generator function.109180Like generator functions, web `TransformStream` can be passed either directly or as a `{transform}` plain object. But `Duplex` and `Transform` must always be passed as a `{transform}` plain object.110Like generator functions, web `TransformStream` can be passed either directly or as a [`{transform}` plain object](../readme.md#transform-options). But `Duplex` and `Transform` must always be passed as a `{transform}` plain object.111182The [`objectMode`](#object-mode) transform option can be used, but not the [`binary`](#encoding) nor [`preserveNewlines`](#newlines) options.112The [`objectMode`](#object-mode) transform option can be used, but not the [`binary`](../readme.md#transformoptionsbinary) nor [`preserveNewlines`](../readme.md#transformoptionspreservenewlines) options.113114```js115import {createGzip} from 'node:zlib';116import {execa} from 'execa';117188const {stdout} = await execa('./run.js', {stdout: {transform: createGzip()}});118const {stdout} = await execa({119 stdout: {transform: createGzip()},120 encoding: 'buffer',121})`npm run build`;122console.log(stdout); // `stdout` is compressed with gzip123```124125```js193import {execa} from 'execa';194195const {stdout} = await execa('./run.js', {stdout: new CompressionStream('gzip')});126const {stdout} = await execa({127 stdout: new CompressionStream('gzip'),128 encoding: 'buffer',129})`npm run build`;130console.log(stdout); // `stdout` is compressed with gzip131```132133## Combining134201The [`stdin`](../readme.md#optionsstdin), [`stdout`](../readme.md#optionsstdout), [`stderr`](../readme.md#optionsstderr) and [`stdio`](../readme.md#optionsstdio) options can accept an array of values. While this is not specific to transforms, this can be useful with them too. For example, the following transform impacts the value printed by `inherit`.135The [`stdin`](../readme.md#optionsstdin), [`stdout`](../readme.md#optionsstdout), [`stderr`](../readme.md#optionsstderr) and [`stdio`](../readme.md#optionsstdio) options can accept [an array of values](output.md#multiple-targets). While this is not specific to transforms, this can be useful with them too. For example, the following transform impacts the value printed by `'inherit'`.136137```js204await execa('echo', ['hello'], {stdout: [transform, 'inherit']});138await execa({stdout: [transform, 'inherit']})`npm run build`;139```140141This also allows using multiple transforms.142143```js210await execa('echo', ['hello'], {stdout: [transform, otherTransform]});144await execa({stdout: [transform, otherTransform]})`npm run build`;145```146213Or saving to files.147Or saving to archives.148149```js216await execa('./run.js', {stdout: [new CompressionStream('gzip'), {file: './output.gz'}]});150await execa({stdout: [new CompressionStream('gzip'), {file: './output.gz'}]})`npm run build`;151```152219## Async iteration153<hr>154221In some cases, [iterating](../readme.md#subprocessiterablereadableoptions) over the subprocess can be an alternative to transforms.222223```js224import {execa} from 'execa';225226for await (const line of execa('./run.js')) {227 const prefix = line.includes('error') ? 'ERROR' : 'INFO';228 console.log(`${prefix}: ${line}`);229}230```231232## Transform options233234A transform or an [array of transforms](#combining) can be passed to the [`stdin`](../readme.md#optionsstdin), [`stdout`](../readme.md#optionsstdout), [`stderr`](../readme.md#optionsstderr) or [`stdio`](../readme.md#optionsstdio) option.235236A transform is either a [generator function](#transformoptionstransform) or a plain object with the following members.237238### transformOptions.transform239240Type: `GeneratorFunction<string | Uint8Array | unknown>` | `AsyncGeneratorFunction<string | Uint8Array | unknown>`241242Map or [filter](#filtering) the input or output of the subprocess.243244More info [here](#summary) and [there](#sharing-state).245246### transformOptions.final247248Type: `GeneratorFunction<string | Uint8Array | unknown>` | `AsyncGeneratorFunction<string | Uint8Array | unknown>`249250Create additional lines after the last one.251252[More info.](#finalizing)253254### transformOptions.binary255256Type: `boolean`\257Default: `false`258259If `true`, iterate over arbitrary chunks of `Uint8Array`s instead of line `string`s.260261More info [here](#encoding) and [there](#binary-data).262263### transformOptions.preserveNewlines264265Type: `boolean`\266Default: `false`267268If `true`, keep newlines in each `line` argument. Also, this allows multiple `yield`s to produces a single line.269270[More info.](#newlines)271272### transformOptions.objectMode273274Type: `boolean`\275Default: `false`276277If `true`, allow [`transformOptions.transform`](#transformoptionstransform) and [`transformOptions.final`](#transformoptionsfinal) to return any type, not just `string` or `Uint8Array`.278279[More info.](#object-mode)155[**Next**: 🔀 Piping multiple subprocesses](pipe.md)\156[**Previous**: 🤖 Binary data](binary.md)\157[**Top**: Table of contents](../readme.md#documentation)
added:docs/windows.md+57 added
modified:lib/pipe/abort.js+1 added-1 removed
8 unmodified lines
910const unpipeOnSignalAbort = async (unpipeSignal, {sourceStream, mergedStream, fileDescriptors, sourceOptions, startTime}) => {11 await aborted(unpipeSignal, sourceStream);12 await mergedStream.remove(sourceStream);13 const error = new Error('Pipe cancelled by `unpipeSignal` option.');13 const error = new Error('Pipe canceled by `unpipeSignal` option.');14 throw createNonCommandError({15 error,16 fileDescriptors,17 sourceOptions,
3 unmodified lines
modified:test/pipe/abort.js+1 added-1 removed
24 unmodified lines
25 t.is(error.all, undefined);26 t.deepEqual(error.stdio, Array.from({length: error.stdio.length}));27 t.deepEqual(error.pipedFrom, []);2829 t.true(error.originalMessage.includes('Pipe cancelled'));29 t.true(error.originalMessage.includes('Pipe canceled'));30 t.true(error.shortMessage.includes(`Command failed: ${error.command}`));31 t.true(error.shortMessage.includes(error.originalMessage));32 t.true(error.message.includes(error.shortMessage));33};
134 unmodified lines
modified:types/arguments/options.d.ts+48 added-118 removed
6 unmodified lines
7export type CommonOptions<IsSync extends boolean = boolean> = {8 /**9 Prefer locally installed binaries when looking for a binary to execute.1011 If you `$ npm install foo`, you can then `execa('foo')`.1211 @default `true` with `$`, `false` otherwise12 */13 readonly preferLocal?: boolean;1415 /**18 Preferred path to find locally installed binaries in (use with `preferLocal`).16 Preferred path to find locally installed binaries, when using the `preferLocal` option.1720 @default process.cwd()18 @default `cwd` option19 */20 readonly localDir?: string | URL;2122 /**
5 unmodified lines
2829 /**30 Path to the Node.js executable.3134 For example, this can be used together with [`get-node`](https://github.com/ehmicky/get-node) to run a specific Node.js version.3532 Requires the `node` option to be `true`.3334 @default [`process.execPath`](https://nodejs.org/api/process.html#process_process_execpath) (current Node.js executable)35 */36 readonly nodePath?: string | URL;3738 /**43 List of [CLI options](https://nodejs.org/api/cli.html#cli_options) passed to the Node.js executable.39 List of [CLI flags](https://nodejs.org/api/cli.html#cli_options) passed to the Node.js executable.4041 Requires the `node` option to be `true`.4243 @default [`process.execArgv`](https://nodejs.org/api/process.html#process_process_execargv) (current Node.js CLI options)44 */45 readonly nodeOptions?: readonly string[];4647 /**52 Write some input to the subprocess' `stdin`.48 Write some input to the subprocess' [`stdin`](https://en.wikipedia.org/wiki/Standard_streams#Standard_input_(stdin)).4950 See also the `inputFile` and `stdin` options.51 */52 readonly input?: string | Uint8Array | Readable;5354 /**59 Use a file as input to the subprocess' `stdin`.55 Use a file as input to the subprocess' [`stdin`](https://en.wikipedia.org/wiki/Standard_streams#Standard_input_(stdin)).5657 See also the `input` and `stdin` options.58 */59 readonly inputFile?: string | URL;6061 /**66 How to setup the subprocess' standard input. This can be:67 - `'pipe'`: Sets `subprocess.stdin` stream.68 - `'overlapped'`: Like `'pipe'` but asynchronous on Windows.69 - `'ignore'`: Do not use `stdin`.70 - `'inherit'`: Re-use the current process' `stdin`.71 - an integer: Re-use a specific file descriptor from the current process.72 - a Node.js `Readable` stream.73 - `{ file: 'path' }` object.74 - a file URL.75 - a web [`ReadableStream`](https://developer.mozilla.org/en-US/docs/Web/API/ReadableStream).76 - an [`Iterable`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#the_iterable_protocol) or an [`AsyncIterable`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#the_async_iterator_and_async_iterable_protocols)77 - an `Uint8Array`.62 How to setup the subprocess' [standard input](https://en.wikipedia.org/wiki/Standard_streams#Standard_input_(stdin)). This can be `'pipe'`, `'overlapped'`, `'ignore`, `'inherit'`, a file descriptor integer, a Node.js `Readable` stream, a web `ReadableStream`, a `{ file: 'path' }` object, a file URL, an `Iterable`, an `AsyncIterable`, an `Uint8Array`, a generator function, a `Duplex` or a web `TransformStream`.6379 This can be an [array of values](https://github.com/sindresorhus/execa#redirect-stdinstdoutstderr-to-multiple-destinations) such as `['inherit', 'pipe']` or `[filePath, 'pipe']`.64 This can be an array of values such as `['inherit', 'pipe']` or `[fileUrl, 'pipe']`.6581 This can also be a generator function or a [`Duplex`](https://nodejs.org/api/stream.html#class-streamduplex) or a [web `TransformStream`](https://developer.mozilla.org/en-US/docs/Web/API/TransformStream) to transform the input. [Learn more.](https://github.com/sindresorhus/execa/tree/main/docs/transform.md)8283 @default `inherit` with `$`, `pipe` otherwise66 @default `'inherit'` with `$`, `'pipe'` otherwise67 */68 readonly stdin?: StdinOptionCommon<IsSync>;6970 /**88 How to setup the subprocess' standard output. This can be:89 - `'pipe'`: Sets `result.stdout` (as a string or `Uint8Array`) and `subprocess.stdout` (as a stream).90 - `'overlapped'`: Like `'pipe'` but asynchronous on Windows.91 - `'ignore'`: Do not use `stdout`.92 - `'inherit'`: Re-use the current process' `stdout`.93 - an integer: Re-use a specific file descriptor from the current process.94 - a Node.js `Writable` stream.95 - `{ file: 'path' }` object.96 - a file URL.97 - a web [`WritableStream`](https://developer.mozilla.org/en-US/docs/Web/API/WritableStream).71 How to setup the subprocess' [standard output](https://en.wikipedia.org/wiki/Standard_streams#Standard_input_(stdin)). This can be `'pipe'`, `'overlapped'`, `'ignore`, `'inherit'`, a file descriptor integer, a Node.js `Writable` stream, a web `WritableStream`, a `{ file: 'path' }` object, a file URL, a generator function, a `Duplex` or a web `TransformStream`.7299 This can be an [array of values](https://github.com/sindresorhus/execa#redirect-stdinstdoutstderr-to-multiple-destinations) such as `['inherit', 'pipe']` or `[filePath, 'pipe']`.73 This can be an array of values such as `['inherit', 'pipe']` or `[fileUrl, 'pipe']`.74101 This can also be a generator function or a [`Duplex`](https://nodejs.org/api/stream.html#class-streamduplex) or a [web `TransformStream`](https://developer.mozilla.org/en-US/docs/Web/API/TransformStream) to transform the output. [Learn more.](https://github.com/sindresorhus/execa/tree/main/docs/transform.md)10275 @default 'pipe'76 */77 readonly stdout?: StdoutStderrOptionCommon<IsSync>;7879 /**108 How to setup the subprocess' standard error. This can be:109 - `'pipe'`: Sets `result.stderr` (as a string or `Uint8Array`) and `subprocess.stderr` (as a stream).110 - `'overlapped'`: Like `'pipe'` but asynchronous on Windows.111 - `'ignore'`: Do not use `stderr`.112 - `'inherit'`: Re-use the current process' `stderr`.113 - an integer: Re-use a specific file descriptor from the current process.114 - a Node.js `Writable` stream.115 - `{ file: 'path' }` object.116 - a file URL.117 - a web [`WritableStream`](https://developer.mozilla.org/en-US/docs/Web/API/WritableStream).80 How to setup the subprocess' [standard error](https://en.wikipedia.org/wiki/Standard_streams#Standard_input_(stdin)). This can be `'pipe'`, `'overlapped'`, `'ignore`, `'inherit'`, a file descriptor integer, a Node.js `Writable` stream, a web `WritableStream`, a `{ file: 'path' }` object, a file URL, a generator function, a `Duplex` or a web `TransformStream`.81119 This can be an [array of values](https://github.com/sindresorhus/execa#redirect-stdinstdoutstderr-to-multiple-destinations) such as `['inherit', 'pipe']` or `[filePath, 'pipe']`.82 This can be an array of values such as `['inherit', 'pipe']` or `[fileUrl, 'pipe']`.83121 This can also be a generator function or a [`Duplex`](https://nodejs.org/api/stream.html#class-streamduplex) or a [web `TransformStream`](https://developer.mozilla.org/en-US/docs/Web/API/TransformStream) to transform the output. [Learn more.](https://github.com/sindresorhus/execa/tree/main/docs/transform.md)12284 @default 'pipe'85 */86 readonly stderr?: StdoutStderrOptionCommon<IsSync>;8788 /**128 Like the `stdin`, `stdout` and `stderr` options but for all file descriptors at once. For example, `{stdio: ['ignore', 'pipe', 'pipe']}` is the same as `{stdin: 'ignore', stdout: 'pipe', stderr: 'pipe'}`.89 Like the `stdin`, `stdout` and `stderr` options but for all [file descriptors](https://en.wikipedia.org/wiki/File_descriptor) at once. For example, `{stdio: ['ignore', 'pipe', 'pipe']}` is the same as `{stdin: 'ignore', stdout: 'pipe', stderr: 'pipe'}`.90130 A single string can be used as a shortcut. For example, `{stdio: 'pipe'}` is the same as `{stdin: 'pipe', stdout: 'pipe', stderr: 'pipe'}`.91 A single string can be used as a shortcut.92132 The array can have more than 3 items, to create additional file descriptors beyond `stdin`/`stdout`/`stderr`. For example, `{stdio: ['pipe', 'pipe', 'pipe', 'pipe']}` sets a fourth file descriptor.93 The array can have more than 3 items, to create additional file descriptors beyond `stdin`/`stdout`/`stderr`.9495 @default 'pipe'96 */97 readonly stdio?: StdioOptionsProperty<IsSync>;
9 unmodified lines
107 */108 readonly lines?: FdGenericOption<boolean>;109110 /**150 Setting this to `false` resolves the promise with the error instead of rejecting it.111 Setting this to `false` resolves the result's promise with the error instead of rejecting it.112113 @default true114 */115 readonly reject?: boolean;
17 unmodified lines
133 */134 readonly extendEnv?: boolean;135136 /**176 Current working directory of the subprocess.137 Current [working directory](https://en.wikipedia.org/wiki/Working_directory) of the subprocess.138139 This is also used to resolve the `nodePath` option when it is a relative path.140141 @default process.cwd()142 */143 readonly cwd?: string | URL;144145 /**185 Environment key-value pairs.146 [Environment variables](https://en.wikipedia.org/wiki/Environment_variable).147148 Unless the `extendEnv` option is `false`, the subprocess also uses the current process' environment variables ([`process.env`](https://nodejs.org/api/process.html#processenv)).149189 @default process.env150 @default [process.env](https://nodejs.org/api/process.html#processenv)151 */152 readonly env?: NodeJS.ProcessEnv;153154 /**194 Explicitly set the value of `argv[0]` sent to the subprocess. This will be set to `command` or `file` if not specified.155 Value of [`argv[0]`](https://nodejs.org/api/process.html#processargv0) sent to the subprocess.156157 @default file being executed158 */159 readonly argv0?: string;160161 /**199 Sets the user identity of the subprocess.162 Sets the [user identifier](https://en.wikipedia.org/wiki/User_identifier) of the subprocess.163164 @default current user identifier165 */166 readonly uid?: number;167168 /**204 Sets the group identity of the subprocess.169 Sets the [group identifier](https://en.wikipedia.org/wiki/Group_identifier) of the subprocess.170171 @default current group identifier172 */173 readonly gid?: number;174175 /**209 If `true`, runs `command` inside of a shell. Uses `/bin/sh` on UNIX and `cmd.exe` on Windows. A different shell can be specified as a string. The shell should understand the `-c` switch on UNIX or `/d /s /c` on Windows.176 If `true`, runs the command inside of a [shell](https://en.wikipedia.org/wiki/Shell_(computing)).177211 We recommend against using this option since it is:212 - not cross-platform, encouraging shell-specific syntax.213 - slower, because of the additional shell interpretation.214 - unsafe, potentially allowing command injection.178 Uses [`/bin/sh`](https://en.wikipedia.org/wiki/Unix_shell) on UNIX and [`cmd.exe`](https://en.wikipedia.org/wiki/Cmd.exe) on Windows. A different shell can be specified as a string. The shell should understand the `-c` switch on UNIX or `/d /s /c` on Windows.179180 We recommend against using this option.181182 @default false183 */184 readonly shell?: boolean | string | URL;185186 /**221 If the subprocess outputs text, specifies its character encoding, either `'utf8'` or `'utf16le'`.187 If the subprocess outputs text, specifies its character encoding, either [`'utf8'`](https://en.wikipedia.org/wiki/UTF-8) or [`'utf16le'`](https://en.wikipedia.org/wiki/UTF-16).188189 If it outputs binary data instead, this should be either:190 - `'buffer'`: returns the binary output as an `Uint8Array`.225 - `'hex'`, `'base64'`, `'base64url'`, [`'latin1'`](https://nodejs.org/api/buffer.html#buffers-and-character-encodings) or [`'ascii'`](https://nodejs.org/api/buffer.html#buffers-and-character-encodings): encodes the binary output as a string.191 - [`'hex'`](https://en.wikipedia.org/wiki/Hexadecimal), [`'base64'`](https://en.wikipedia.org/wiki/Base64), [`'base64url'`](https://en.wikipedia.org/wiki/Base64#URL_applications), [`'latin1'`](https://nodejs.org/api/buffer.html#buffers-and-character-encodings) or [`'ascii'`](https://nodejs.org/api/buffer.html#buffers-and-character-encodings): encodes the binary output as a string.192193 The output is available with `result.stdout`, `result.stderr` and `result.stdio`.194195 @default 'utf8'
2 unmodified lines
198199 /**200 If `timeout` is greater than `0`, the subprocess will be terminated if it runs for longer than that amount of milliseconds.201202 On timeout, `result.timedOut` becomes `true`.203204 @default 0205 */206 readonly timeout?: number;207208 /**209 Largest amount of data allowed on `stdout`, `stderr` and `stdio`.210243 When this threshold is hit, the subprocess fails and `error.isMaxBuffer` becomes `true`.244245 This is measured:246 - By default: in [characters](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/length).247 - If the `encoding` option is `'buffer'`: in bytes.248 - If the `lines` option is `true`: in lines.249 - If a transform in object mode is used: in objects.250211 By default, this applies to both `stdout` and `stderr`, but different values can also be passed.212213 @default 100_000_000214 */215 readonly maxBuffer?: FdGenericOption<number>;216217 /**258 Signal used to terminate the subprocess when:259 - using the `cancelSignal`, `timeout`, `maxBuffer` or `cleanup` option260 - calling `subprocess.kill()` with no arguments218 Default [signal](https://en.wikipedia.org/wiki/Signal_(IPC)) used to terminate the subprocess.219262 This can be either a name (like `"SIGTERM"`) or a number (like `9`).220 This can be either a name (like `'SIGTERM'`) or a number (like `9`).221222 @default 'SIGTERM'223 */224 readonly killSignal?: string | number;225226 /**227 If the subprocess is terminated but does not exit, forcefully exit it by sending [`SIGKILL`](https://en.wikipedia.org/wiki/Signal_(IPC)#SIGKILL).228271 The grace period is 5 seconds by default. This feature can be disabled with `false`.272273 This works when the subprocess is terminated by either:274 - the `cancelSignal`, `timeout`, `maxBuffer` or `cleanup` option275 - calling `subprocess.kill()` with no arguments276277 This does not work when the subprocess is terminated by either:278 - calling `subprocess.kill()` with an argument279 - calling [`process.kill(subprocess.pid)`](https://nodejs.org/api/process.html#processkillpid-signal)280 - sending a termination signal from another process281282 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.283229 @default 5000230 */231 readonly forceKillAfterDelay?: Unless<IsSync, number | false>;232233 /**289 If `true`, no quoting or escaping of arguments is done on Windows. Ignored on other platforms. This is set to `true` automatically when the `shell` option is `true`.234 If `false`, escapes the command arguments on Windows.235291 @default false236 @default `true` if the `shell` option is `true`, `false` otherwise237 */238 readonly windowsVerbatimArguments?: boolean;239240 /**296 On Windows, do not create a new console window. Please note this also prevents `CTRL-C` [from working](https://github.com/nodejs/node/issues/29837) on Windows.241 On Windows, do not create a new console window.242243 @default true244 */245 readonly windowsHide?: boolean;246247 /**303 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.248 If `verbose` is `'short'`, prints the command on [`stderr`](https://en.wikipedia.org/wiki/Standard_streams#Standard_error_(stderr)): its file, arguments, duration and (if it failed) error message.249305 If `verbose` is `'full'`, the command's `stdout` and `stderr` are printed too, unless either:306 - the `stdout`/`stderr` option is `ignore` or `inherit`.307 - the `stdout`/`stderr` is redirected to [a stream](https://nodejs.org/api/stream.html#readablepipedestination-options), a file, a file descriptor, or another subprocess.308 - the `encoding` option is binary.250 If `verbose` is `'full'`, the command's [`stdout`](https://en.wikipedia.org/wiki/Standard_streams#Standard_output_(stdout)) and `stderr` are also printed.251310 This can also be set to `'full'` by setting the `NODE_DEBUG=execa` environment variable in the current process.311252 By default, this applies to both `stdout` and `stderr`, but different values can also be passed.253254 @default 'none'255 */256 readonly verbose?: FdGenericOption<'none' | 'short' | 'full'>;257258 /**319 Kill the subprocess when the current process exits unless either:320 - the subprocess is `detached`.321 - the current process is terminated abruptly, for example, with `SIGKILL` as opposed to `SIGTERM` or a normal exit.259 Kill the subprocess when the current process exits.260261 @default true262 */263 readonly cleanup?: Unless<IsSync, boolean>;264265 /**328 Whether to return the subprocess' output using the `result.stdout`, `result.stderr`, `result.all` and `result.stdio` properties.266 When `buffer` is `false`, the `result.stdout`, `result.stderr`, `result.all` and `result.stdio` properties are not set.267330 On failure, the `error.stdout`, `error.stderr`, `error.all` and `error.stdio` properties are used instead.331332 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.333268 By default, this applies to both `stdout` and `stderr`, but different values can also be passed.269270 @default true271 */272 readonly buffer?: FdGenericOption<boolean>;273274 /**341 Add a `subprocess.all` stream and a `result.all` property. They contain the combined/[interleaved](#ensuring-all-output-is-interleaved) output of the subprocess' `stdout` and `stderr`.275 Add a `subprocess.all` stream and a `result.all` property. They contain the combined/interleaved output of the subprocess' `stdout` and `stderr`.276277 @default false278 */279 readonly all?: boolean;
5 unmodified lines
285 */286 readonly ipc?: Unless<IsSync, boolean>;287288 /**355 Specify the kind of serialization used for sending messages between subprocesses when using the `ipc` option:356 - `json`: Uses `JSON.stringify()` and `JSON.parse()`.357 - `advanced`: Uses [`v8.serialize()`](https://nodejs.org/api/v8.html#v8_v8_serialize_value)289 Specify the kind of serialization used for sending messages between subprocesses when using the `ipc` option.290359 [More info.](https://nodejs.org/api/child_process.html#child_process_advanced_serialization)360291 @default 'advanced'292 */293 readonly serialization?: Unless<IsSync, 'json' | 'advanced'>;294295 /**366 Prepare subprocess to run independently of the current process. Specific behavior depends on the platform.296 Run the subprocess independently from the current process.297298 @default false299 */300 readonly detached?: Unless<IsSync, boolean>;
60 unmodified lines
modified:types/methods/command.d.ts+1 added-14 removed
13 unmodified lines
14 ): ExecaSubprocess<OptionsType & NewOptionsType>;15};1617/**18`execa` with the template string syntax allows the `file` or the `arguments` to be user-defined (by injecting them with `${}`). However, if _both_ the `file` and the `arguments` are user-defined, _and_ those are supplied as a single string, then `execaCommand(command)` must be used instead.18Executes a command. `command` is a string that includes both the `file` and its `arguments`.1920This is only intended for very specific cases, such as a REPL. This should be avoided otherwise.2122Just like `execa()`, this can bind options. It can also be run synchronously using `execaCommandSync()`.2324Arguments are automatically escaped. They can contain any character, but spaces must be escaped with a backslash like `execaCommand('echo has\\ space')`.2524@param command - The program/script to execute and its arguments.25@returns An `ExecaSubprocess` that is both:26- a `Promise` resolving or rejecting with a subprocess `result`.27- a [`child_process` instance](https://nodejs.org/api/child_process.html#child_process_class_childprocess) with some additional methods and properties.
25 unmodified lines
53Same as `execaCommand()` but synchronous.5455Returns or throws a subprocess `result`. The `subprocess` is not returned: its methods and properties are not available.5659The following features cannot be used:60- Streams: `subprocess.stdin`, `subprocess.stdout`, `subprocess.stderr`, `subprocess.readable()`, `subprocess.writable()`, `subprocess.duplex()`.61- The `stdin`, `stdout`, `stderr` and `stdio` options cannot be `'overlapped'`, an async iterable, an async transform, a `Duplex`, nor a web stream. Node.js streams can be passed but only if either they [have a file descriptor](#redirect-a-nodejs-stream-fromto-stdinstdoutstderr), or the `input` option is used.62- Signal termination: `subprocess.kill()`, `subprocess.pid`, `cleanup` option, `cancelSignal` option, `forceKillAfterDelay` option.63- Piping multiple processes: `subprocess.pipe()`.64- `subprocess.iterable()`.65- `ipc` and `serialization` options.66- `result.all` is not interleaved.67- `detached` option.68- The `maxBuffer` option is always measured in bytes, not in characters, lines nor objects. Also, it ignores transforms and the `encoding` option.6957@param command - The program/script to execute and its arguments.58@returns A subprocess `result` object59@throws A subprocess `result` error60
10 unmodified lines
modified:types/methods/main-async.d.ts+1 added-9 removed
20 unmodified lines
2122/**23Executes a command using `file ...arguments`.2425Arguments are automatically escaped. They can contain any character, including spaces, tabs and newlines.2625When `command` is a template string, it includes both the `file` and its `arguments`.2629The `command` template string can inject any `${value}` with the following types: string, number, `subprocess` or an array of those types. For example: `` execa`echo one ${'two'} ${3} ${['four', 'five']}` ``. For `${subprocess}`, the subprocess's `stdout` is used.27`execa(options)` can be used to return a new instance of Execa but with different default `options`. Consecutive calls are merged to previous ones.2831When `command` is a template string, arguments can contain any character, but spaces, tabs and newlines must use `${}` like `` execa`echo ${'has space'}` ``.3233The `command` template string can use multiple lines and indentation.3435`execa(options)` can be used to return a new instance of Execa but with different default `options`. Consecutive calls are merged to previous ones. This allows setting global options or sharing options between multiple commands.3629@param file - The program/script to execute, as a string or file URL30@param arguments - Arguments to pass to `file` on execution.31@returns An `ExecaSubprocess` that is both:32- a `Promise` resolving or rejecting with a subprocess `result`.
162 unmodified lines
modified:types/methods/main-sync.d.ts-11 removed
22 unmodified lines
23Same as `execa()` but synchronous.2425Returns or throws a subprocess `result`. The `subprocess` is not returned: its methods and properties are not available.2627The following features cannot be used:28- Streams: `subprocess.stdin`, `subprocess.stdout`, `subprocess.stderr`, `subprocess.readable()`, `subprocess.writable()`, `subprocess.duplex()`.29- The `stdin`, `stdout`, `stderr` and `stdio` options cannot be `'overlapped'`, an async iterable, an async transform, a `Duplex`, nor a web stream. Node.js streams can be passed but only if either they [have a file descriptor](#redirect-a-nodejs-stream-fromto-stdinstdoutstderr), or the `input` option is used.30- Signal termination: `subprocess.kill()`, `subprocess.pid`, `cleanup` option, `cancelSignal` option, `forceKillAfterDelay` option.31- Piping multiple processes: `subprocess.pipe()`.32- `subprocess.iterable()`.33- `ipc` and `serialization` options.34- `result.all` is not interleaved.35- `detached` option.36- The `maxBuffer` option is always measured in bytes, not in characters, lines nor objects. Also, it ignores transforms and the `encoding` option.3727@param file - The program/script to execute, as a string or file URL28@param arguments - Arguments to pass to `file` on execution.29@returns A subprocess `result` object30@throws A subprocess `result` error
55 unmodified lines
modified:types/methods/script.d.ts+1 added-1 removed
46 unmodified lines
47 s: ExecaScriptSync<OptionsType>;48} & ExecaScriptCommon<OptionsType>;4950/**51Same as `execa()` but using the `stdin: 'inherit'` and `preferLocal: true` options.51Same as `execa()` but using script-friendly default options.5253Just like `execa()`, this can use the template string syntax or bind options. It can also be run synchronously using `$.sync()` or `$.s()`.5455This is the preferred method when executing multiple commands in a script file.
30 unmodified lines
modified:types/return/final-error.d.ts+2 added-12 removed
22 unmodified lines
23 | 'originalMessage'24 | 'code';2526/**27Exception thrown when the subprocess fails, either:28- its exit code is not `0`29- it was terminated with a signal, including `subprocess.kill()`30- timing out31- being canceled32- there's not enough memory or there are already too many subprocesses27Exception thrown when the subprocess fails.2829This has the same shape as successful results, with a few additional properties.30*/31export class ExecaError<OptionsType extends Options = Options> extends CommonError<false, OptionsType> {32 readonly name: 'ExecaError';33}3435/**41Exception thrown when the subprocess fails, either:42- its exit code is not `0`43- it was terminated with a signal, including `.kill()`44- timing out45- being canceled46- there's not enough memory or there are already too many subprocesses36Exception thrown when the subprocess fails.3738This has the same shape as successful results, with a few additional properties.39*/40export class ExecaSyncError<OptionsType extends SyncOptions = SyncOptions> extends CommonError<true, OptionsType> {
2 unmodified lines
modified:types/return/result.d.ts+31 added-34 removed
8 unmodified lines
9 IsSync extends boolean = boolean,10 OptionsType extends CommonOptions = CommonOptions,11> {12 /**13 The file and arguments that were run, for logging purposes.1415 This is not escaped and should not be executed directly as a subprocess, including using `execa()` or `execaCommand()`.13 The file and arguments that were run.14 */15 command: string;1617 /**18 Same as `command` but escaped.2122 Unlike `command`, control characters are escaped, which makes it safe to print in a terminal.2324 This can also be copied and pasted into a shell, for debugging purposes.25 Since the escaping is fairly basic, this should not be executed directly as a subprocess, including using `execa()` or `execaCommand()`.19 */20 escapedCommand: string;2122 /**30 The numeric exit code of the subprocess that was run.23 The numeric [exit code](https://en.wikipedia.org/wiki/Exit_status) of the subprocess that was run.2425 This is `undefined` when the subprocess could not be spawned or was terminated by a signal.26 */27 exitCode?: number;2829 /**37 The output of the subprocess on `stdout`.30 The output of the subprocess on [`stdout`](https://en.wikipedia.org/wiki/Standard_streams#Standard_output_(stdout)).3139 This is `undefined` if the `stdout` option is set to only `'inherit'`, `'ignore'`, `Writable` or `integer`. This is an array if the `lines` option is `true`, or if the `stdout` option is a transform in object mode.32 This is `undefined` if the `stdout` option is set to only `'inherit'`, `'ignore'`, `Writable` or `integer`, or if the `buffer` option is `false`.3334 This is an array if the `lines` option is `true`, or if the `stdout` option is a transform in object mode.35 */36 stdout: ResultStdioNotAll<'1', OptionsType>;3738 /**44 The output of the subprocess on `stderr`.39 The output of the subprocess on [`stderr`](https://en.wikipedia.org/wiki/Standard_streams#Standard_error_(stderr)).4046 This is `undefined` if the `stderr` option is set to only `'inherit'`, `'ignore'`, `Writable` or `integer`. This is an array if the `lines` option is `true`, or if the `stderr` option is a transform in object mode.41 This is `undefined` if the `stderr` option is set to only `'inherit'`, `'ignore'`, `Writable` or `integer`, or if the `buffer` option is `false`.4243 This is an array if the `lines` option is `true`, or if the `stderr` option is a transform in object mode.44 */45 stderr: ResultStdioNotAll<'2', OptionsType>;4647 /**48 The output of the subprocess with `result.stdout` and `result.stderr` interleaved.4950 This requires the `all` option to be `true`.5152 This is `undefined` if both `stdout` and `stderr` options are set to only `'inherit'`, `'ignore'`, `Writable` or `integer`, or if the `buffer` option is `false`.5354 This is an array if the `lines` option is `true`, or if either the `stdout` or `stderr` option is a transform in object mode.55 */56 all: ResultAll<OptionsType>;5758 /**59 The output of the subprocess on `stdin`, `stdout`, `stderr` and other file descriptors.6053 Items are `undefined` when their corresponding `stdio` option is set to only `'inherit'`, `'ignore'`, `Writable` or `integer`. Items are arrays when their corresponding `stdio` option is a transform in object mode.61 Items are `undefined` when their corresponding `stdio` option is set to only `'inherit'`, `'ignore'`, `Writable` or `integer`, or if the `buffer` option is `false`.6263 Items are arrays when their corresponding `stdio` option is a transform in object mode.64 */65 stdio: ResultStdioArray<OptionsType>;6667 /**
1 unmodified line
69 */70 failed: boolean;7172 /**63 Whether the subprocess timed out.73 Whether the subprocess timed out due to the `timeout` option.74 */75 timedOut: boolean;7677 /**
12 unmodified lines
90 */91 signal?: string;9293 /**84 A human-friendly description of the signal that was used to terminate the subprocess. For example, `Floating point arithmetic error`.94 A human-friendly description of the signal that was used to terminate the subprocess.9596 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.97 */98 signalDescription?: string;
18 unmodified lines
117 */118 isMaxBuffer: boolean;119120 /**111 The output of the subprocess with `result.stdout` and `result.stderr` interleaved.121 Results of the other subprocesses that were piped into this subprocess.122113 This is `undefined` if either:114 - the `all` option is `false` (default value).115 - both `stdout` and `stderr` options are set to `'inherit'`, `'ignore'`, `Writable` or `integer`.116117 This is an array if the `lines` option is `true`, or if either the `stdout` or `stderr` option is a transform in object mode.118 */119 all: ResultAll<OptionsType>;120121 /**122 Results of the other subprocesses that were piped into this subprocess. This is useful to inspect a series of subprocesses piped with each other.123123 This array is initially empty and is populated each time the `subprocess.pipe()` method resolves.124 */125 pipedFrom: Unless<IsSync, ExecaResult[], []>;126127 /**129 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.130131 The subprocess `stderr`, `stdout` and other file descriptors' output are appended to the end, separated with newlines and not interleaved.128 Error message when the subprocess failed to run.129 */130 message?: string;131132 /**136 This is the same as the `message` property except it does not include the subprocess `stdout`/`stderr`/`stdio`.133 This is the same as `error.message` except it does not include the subprocess output.134 */135 shortMessage?: string;136137 /**141 Original error message. This is the same as the `message` property excluding the subprocess `stdout`/`stderr`/`stdio` and some additional information added by Execa.138 Original error message. This is the same as `error.message` excluding the subprocess output and some additional information added by Execa.139143 This exists only if the subprocess exited due to an `error` event or a timeout.140 This exists only in specific instances, such as during a timeout.141 */142 originalMessage?: string;143144 /**
43 unmodified lines
modified:types/subprocess/subprocess.d.ts+8 added-32 removed
39 unmodified lines
40 */41 send: HasIpc<OptionsType> extends true ? ChildProcess['send'] : undefined;4243 /**44 The subprocess `stdin` as a stream.44 The subprocess [`stdin`](https://en.wikipedia.org/wiki/Standard_streams#Standard_input_(stdin)) as a stream.4546 This is `null` if the `stdin` option is set to `'inherit'`, `'ignore'`, `Readable` or `integer`.4748 This is intended for advanced cases. Please consider using the `stdin` option, `input` option, `inputFile` option, or `subprocess.pipe()` instead.47 */48 stdin: SubprocessStdioStream<'0', OptionsType>;4950 /**53 The subprocess `stdout` as a stream.51 The subprocess [`stdout`](https://en.wikipedia.org/wiki/Standard_streams#Standard_output_(stdout)) as a stream.5255 This is `null` if the `stdout` option is set to `'inherit'`, `'ignore'`, `Writable` or `integer`.5657 This is intended for advanced cases. Please consider using `result.stdout`, the `stdout` option, `subprocess.iterable()`, or `subprocess.pipe()` instead.53 This is `null` if the `stdout` option is set to `'inherit'`, `'ignore'`, `Writable` or `integer`, or if the `buffer` option is `false`.54 */55 stdout: SubprocessStdioStream<'1', OptionsType>;5657 /**62 The subprocess `stderr` as a stream.58 The subprocess [`stderr`](https://en.wikipedia.org/wiki/Standard_streams#Standard_error_(stderr)) as a stream.5964 This is `null` if the `stderr` option is set to `'inherit'`, `'ignore'`, `Writable` or `integer`.6566 This is intended for advanced cases. Please consider using `result.stderr`, the `stderr` option, `subprocess.iterable()`, or `subprocess.pipe()` instead.60 This is `null` if the `stderr` option is set to `'inherit'`, `'ignore'`, `Writable` or `integer`, or if the `buffer` option is `false`.61 */62 stderr: SubprocessStdioStream<'2', OptionsType>;6364 /**65 Stream combining/interleaving `subprocess.stdout` and `subprocess.stderr`.6673 This is `undefined` if either:74 - the `all` option is `false` (the default value).75 - both `stdout` and `stderr` options are set to `'inherit'`, `'ignore'`, `Writable` or `integer`.67 This requires the `all` option to be `true`.6877 This is intended for advanced cases. Please consider using `result.all`, the `stdout`/`stderr` option, `subprocess.iterable()`, or `subprocess.pipe()` instead.69 This is `undefined` if `stdout` and `stderr` options are set to `'inherit'`, `'ignore'`, `Writable` or `integer`, or if the `buffer` option is `false`.70 */71 all: SubprocessAll<OptionsType>;7273 /**74 The subprocess `stdin`, `stdout`, `stderr` and other files descriptors as an array of streams.7584 Each array item is `null` if the corresponding `stdin`, `stdout`, `stderr` or `stdio` option is set to `'inherit'`, `'ignore'`, `Stream` or `integer`.8586 This is intended for advanced cases. Please consider using `result.stdio`, the `stdio` option, `subprocess.iterable()` or `subprocess.pipe()` instead.76 Each array item is `null` if the corresponding `stdin`, `stdout`, `stderr` or `stdio` option is set to `'inherit'`, `'ignore'`, `Stream` or `integer`, or if the `buffer` option is `false`.77 */78 stdio: SubprocessStdioArray<OptionsType>;7980 /**
9 unmodified lines
90 kill(error?: Error): ReturnType<ChildProcess['kill']>;9192 /**93 Subprocesses are [async iterables](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol/asyncIterator). They iterate over each output line.104105 The iteration waits for the subprocess to end. It throws if the subprocess fails. This means you do not need to `await` the subprocess' promise.94 */95 [Symbol.asyncIterator](): SubprocessAsyncIterable<undefined, OptionsType['encoding']>;9697 /**
2 unmodified lines
100 iterable<IterableOptions extends ReadableOptions = {}>(readableOptions?: IterableOptions): SubprocessAsyncIterable<IterableOptions['binary'], OptionsType['encoding']>;101102 /**103 Converts the subprocess to a readable stream.116117 Unlike `subprocess.stdout`, the stream waits for the subprocess to end and emits an [`error`](https://nodejs.org/api/stream.html#event-error) event if the subprocess fails. This means you do not need to `await` the subprocess' promise. On the other hand, you do need to handle to the stream `error` event. This can be done by using [`await finished(stream)`](https://nodejs.org/api/stream.html#streamfinishedstream-options), [`await pipeline(..., stream)`](https://nodejs.org/api/stream.html#streampipelinesource-transforms-destination-options) or [`await text(stream)`](https://nodejs.org/api/webstreams.html#streamconsumerstextstream) which throw an exception when the stream errors.118119 Before using this method, please first consider the `stdin`/`stdout`/`stderr`/`stdio` options, `subprocess.pipe()` or `subprocess.iterable()`.104 */105 readable(readableOptions?: ReadableOptions): Readable;106107 /**108 Converts the subprocess to a writable stream.125126 Unlike `subprocess.stdin`, the stream waits for the subprocess to end and emits an [`error`](https://nodejs.org/api/stream.html#event-error) event if the subprocess fails. This means you do not need to `await` the subprocess' promise. On the other hand, you do need to handle to the stream `error` event. This can be done by using [`await finished(stream)`](https://nodejs.org/api/stream.html#streamfinishedstream-options) or [`await pipeline(stream, ...)`](https://nodejs.org/api/stream.html#streampipelinesource-transforms-destination-options) which throw an exception when the stream errors.127128 Before using this method, please first consider the `stdin`/`stdout`/`stderr`/`stdio` options or `subprocess.pipe()`.109 */110 writable(writableOptions?: WritableOptions): Writable;111112 /**113 Converts the subprocess to a duplex stream.134135 The stream waits for the subprocess to end and emits an [`error`](https://nodejs.org/api/stream.html#event-error) event if the subprocess fails. This means you do not need to `await` the subprocess' promise. On the other hand, you do need to handle to the stream `error` event. This can be done by using [`await finished(stream)`](https://nodejs.org/api/stream.html#streamfinishedstream-options), [`await pipeline(..., stream, ...)`](https://nodejs.org/api/stream.html#streampipelinesource-transforms-destination-options) or [`await text(stream)`](https://nodejs.org/api/webstreams.html#streamconsumerstextstream) which throw an exception when the stream errors.136137 Before using this method, please first consider the `stdin`/`stdout`/`stderr`/`stdio` options, `subprocess.pipe()` or `subprocess.iterable()`.114 */115 duplex(duplexOptions?: DuplexOptions): Duplex;116} & PipableSubprocess;117
3 unmodified lines
modified:types/convert.d.ts+5 added-5 removed
3 unmodified lines
45// `subprocess.readable|duplex|iterable()` options6export type ReadableOptions = {7 /**8 Which stream to read from the subprocess. A file descriptor like `"fd3"` can also be passed.8 Which stream to read from the subprocess. A [file descriptor](https://en.wikipedia.org/wiki/File_descriptor) like `"fd3"` can also be passed.910 `"all"` reads both `stdout` and `stderr`. This requires the `all` option to be `true`.1112 @default 'stdout'13 */14 readonly from?: FromOption;1516 /**17 If `false`, the stream iterates over lines. Each line is a string. Also, the stream is in [object mode](https://nodejs.org/api/stream.html#object-mode).17 If `false`, iterates over lines. Each line is a string.1819 If `true`, the stream iterates over arbitrary chunks of data. Each line is an `Uint8Array` (with `subprocess.iterable()`) or a [`Buffer`](https://nodejs.org/api/buffer.html#class-buffer) (otherwise).19 If `true`, iterates over arbitrary chunks of data. Each line is an [`Uint8Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array) (with `subprocess.iterable()`) or a [`Buffer`](https://nodejs.org/api/buffer.html#class-buffer) (with `subprocess.readable()`/`subprocess.duplex()`).2021 This is always `true` when the `encoding` option is binary.2223 @default `false` with `subprocess.iterable()`, `true` otherwise24 */25 readonly binary?: boolean;2627 /**28 If both this option and the `binary` option is `false`, newlines are stripped from each line.28 If both this option and the `binary` option is `false`, [newlines](https://en.wikipedia.org/wiki/Newline) are stripped from each line.2930 @default `false` with `subprocess.iterable()`, `true` otherwise31 */32 readonly preserveNewlines?: boolean;
1 unmodified line
3435// `subprocess.writable|duplex()` options36export type WritableOptions = {37 /**38 Which stream to write to the subprocess. A file descriptor like `"fd3"` can also be passed.38 Which stream to write to the subprocess. A [file descriptor](https://en.wikipedia.org/wiki/File_descriptor) like `"fd3"` can also be passed.3940 @default 'stdin'41 */42 readonly to?: ToOption;
16 unmodified lines
modified:types/pipe.d.ts+2 added-10 removed
5 unmodified lines
67// `subprocess.pipe()` options8type PipeOptions = {9 /**10 Which stream to pipe from the source subprocess. A file descriptor like `"fd3"` can also be passed.10 Which stream to pipe from the source subprocess. A [file descriptor](https://en.wikipedia.org/wiki/File_descriptor) like `"fd3"` can also be passed.1112 `"all"` pipes both `stdout` and `stderr`. This requires the `all` option to be `true`.13 */14 readonly from?: FromOption;1516 /**17 Which stream to pipe to the destination subprocess. A file descriptor like `"fd3"` can also be passed.17 Which stream to pipe to the destination subprocess. A [file descriptor](https://en.wikipedia.org/wiki/File_descriptor) like `"fd3"` can also be passed.18 */19 readonly to?: ToOption;2021 /**22 Unpipe the subprocess when the signal aborts.2324 The `subprocess.pipe()` method will be rejected with a cancellation error.23 */24 readonly unpipeSignal?: AbortSignal;25};26
2 unmodified lines
29 /**30 [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.3132 This follows the same syntax as `execa(file, arguments?, options?)` except both regular options and pipe-specific options can be specified.3536 This can be called multiple times to chain a series of subprocesses.3738 Multiple subprocesses can be piped to the same subprocess. Conversely, the same subprocess can be piped to multiple other subprocesses.33 */34 pipe<OptionsType extends Options & PipeOptions = {}>(35 file: string | URL,36 arguments?: readonly string[],
14 unmodified lines
51 => Promise<ExecaResult<OptionsType>> & PipableSubprocess;5253 /**54 Like `subprocess.pipe(file, arguments?, options?)` but using the return value of another `execa()` call instead.6162 This is the most advanced method to pipe subprocesses. It is useful in specific cases, such as piping multiple subprocesses to the same subprocess.55 */56 pipe<Destination extends ExecaSubprocess>(destination: Destination, options?: PipeOptions):57 Promise<Awaited<Destination>> & PipableSubprocess;58};
modified:readme.md+336 added-354 removed
45 unmodified lines
46## Why4748This package improves [`child_process`](https://nodejs.org/api/child_process.html) methods with:4950- [Promise interface](#execafile-arguments-options).51- [Script interface](docs/scripts.md) and [template strings](#template-string-syntax), 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](#optionspreferlocal) without `npx`.54- [Cleans up](#optionscleanup) subprocesses when the current process ends.55- Redirect [`stdin`](#optionsstdin)/[`stdout`](#optionsstdout)/[`stderr`](#optionsstderr) from/to files, streams, iterables, strings, `Uint8Array` or [objects](docs/transform.md#object-mode).50- [Promise interface](docs/execution.md).51- [Script interface](docs/scripts.md) and [template strings](docs/execution.md#template-string-syntax), like `zx`.52- Improved [Windows support](docs/windows.md), including [shebang](docs/windows.md#shebang) binaries.53- Executes [locally installed binaries](docs/environment.md#local-binaries) without `npx`.54- [Cleans up](docs/termination.md#current-process-exit) subprocesses when the current process ends.55- Redirect [`stdin`](docs/input.md)/[`stdout`](docs/output.md)/[`stderr`](docs/output.md) from/to [files](docs/output.md#file-output), [streams](docs/streams.md), [iterables](docs/streams.md#iterables-as-input), [strings](docs/input.md#string-input), [`Uint8Array`](docs/binary.md#binary-input) 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 subprocess.58- [Fail-safe subprocess termination](#optionsforcekillafterdelay).59- Get [interleaved output](#optionsall) from `stdout` and `stderr` similar to what is printed on the terminal.60- [Strips the final newline](#optionsstripfinalnewline) from the output so you don't have to do `stdout.trim()`.61- Convenience methods to pipe subprocesses' [input](#redirect-input-from-a-file) and [output](#redirect-output-to-a-file).62- [Verbose mode](#verbose-mode) for debugging.63- More descriptive errors.64- Higher max buffer: 100 MB instead of 1 MB.57- Iterate over [each text line](docs/lines.md#progressive-splitting) output by the subprocess.58- [Fail-safe subprocess termination](docs/termination.md#forceful-termination).59- Get [interleaved output](docs/output.md#interleaved-output) from `stdout` and `stderr` similar to what is printed on the terminal.60- [Strips the final newline](docs/lines.md#final-newline) from the output so you don't have to do `stdout.trim()`.61- Convenience methods to [pipe multiple subprocesses](docs/pipe.md).62- [Verbose mode](docs/debugging.md#verbose-mode) for debugging.63- More descriptive [errors](docs/errors.md).64- Higher [max buffer](docs/output.md#big-output): 100 MB instead of 1 MB.6566## Install6768```sh69npm install execa70```7172## Documentation7374Execution:75- ▶️ [Basic execution](docs/execution.md)76- 💬 [Escaping/quoting](docs/escaping.md)77- 💻 [Shell](docs/shell.md)78- 📜 [Scripts](docs/scripts.md)79- 🐢 [Node.js files](docs/node.md)80- 🌐 [Environment](docs/environment.md)81- ❌ [Errors](docs/errors.md)82- 🏁 [Termination](docs/termination.md)8384Input/output:85- 🎹 [Input](docs/input.md)86- 📢 [Output](docs/output.md)87- 📃 [Text lines](docs/lines.md)88- 🤖 [Binary data](docs/binary.md)89- 🧙 [Transforms](docs/transform.md)9091Advanced usage:92- 🔀 [Piping multiple subprocesses](docs/pipe.md)93- ⏳️ [Streams](docs/streams.md)94- 📞 [Inter-process communication](docs/ipc.md)95- 🐛 [Debugging](docs/debugging.md)96- 📎 [Windows](docs/windows.md)97- 🔍 [Difference with Bash and zx](docs/bash.md)9899## Usage100101### Promise interface102
50 unmodified lines
153```154155### Scripts156130For more information about Execa scripts, please see [this page](docs/scripts.md).131157#### Basic158159```js160import {$} from 'execa';
150 unmodified lines
311_Returns_: [`Subprocess`](#subprocess)312313Executes a command using `file ...arguments`.314290Arguments are [automatically escaped](#shell-syntax). They can contain any character, including spaces, tabs and newlines.315More info on the [syntax](docs/execution.md#array-syntax) and [escaping](docs/escaping.md#array-syntax).316317#### execa\`command\`318#### execa(options)\`command\`319320`command`: `string`\321`options`: [`Options`](#options)\322_Returns_: [`Subprocess`](#subprocess)323299Executes a command. `command` is a [template string](#template-string-syntax) and includes both the `file` and its `arguments`.324Executes a command. `command` is a [template string](docs/execution.md#template-string-syntax) that includes both the `file` and its `arguments`.325301The `command` template string can inject any `${value}` with the following types: string, number, [`subprocess`](#subprocess) or an array of those types. For example: `` execa`echo one ${'two'} ${3} ${['four', 'five']}` ``. For `${subprocess}`, the subprocess's [`stdout`](#resultstdout) is used.326More info on the [syntax](docs/execution.md#template-string-syntax) and [escaping](docs/escaping.md#template-string-syntax).327303Arguments are [automatically escaped](#shell-syntax). They can contain any character, but spaces, tabs and newlines must use `${}` like `` execa`echo ${'has space'}` ``.304305The `command` template string can use [multiple lines and indentation](docs/scripts.md#multiline-commands).306328#### execa(options)329330`options`: [`Options`](#options)\331_Returns_: [`execa`](#execafile-arguments-options)332333Returns a new instance of Execa but with different default [`options`](#options). Consecutive calls are merged to previous ones.334314This allows setting global options or [sharing options](#globalshared-options) between multiple commands.335[More info.](docs/execution.md#globalshared-options)336337#### execaSync(file, arguments?, options?)338#### execaSync\`command\`339340Same as [`execa()`](#execafile-arguments-options) but synchronous.341342Returns or throws a subprocess [`result`](#result). The [`subprocess`](#subprocess) is not returned: its methods and properties are not available.343323The following features cannot be used:324- Streams: [`subprocess.stdin`](#subprocessstdin), [`subprocess.stdout`](#subprocessstdout), [`subprocess.stderr`](#subprocessstderr), [`subprocess.readable()`](#subprocessreadablereadableoptions), [`subprocess.writable()`](#subprocesswritablewritableoptions), [`subprocess.duplex()`](#subprocessduplexduplexoptions).325- The [`stdin`](#optionsstdin), [`stdout`](#optionsstdout), [`stderr`](#optionsstderr) and [`stdio`](#optionsstdio) options cannot be [`'overlapped'`](#optionsstdout), an async iterable, an async [transform](docs/transform.md), a [`Duplex`](docs/transform.md#duplextransform-streams), nor a web stream. Node.js streams can be passed but only if either they [have a file descriptor](#redirect-a-nodejs-stream-fromto-stdinstdoutstderr), or the `input` option is used.326- Signal termination: [`subprocess.kill()`](#subprocesskillerror), [`subprocess.pid`](#subprocesspid), [`cleanup`](#optionscleanup) option, [`cancelSignal`](#optionscancelsignal) option, [`forceKillAfterDelay`](#optionsforcekillafterdelay) option.327- Piping multiple processes: [`subprocess.pipe()`](#subprocesspipefile-arguments-options).328- [`subprocess.iterable()`](#subprocessiterablereadableoptions).329- [`ipc`](#optionsipc) and [`serialization`](#optionsserialization) options.330- [`result.all`](#resultall) is not interleaved.331- [`detached`](#optionsdetached) option.332- The [`maxBuffer`](#optionsmaxbuffer) option is always measured in bytes, not in characters, [lines](#optionslines) nor [objects](docs/transform.md#object-mode). Also, it ignores transforms and the [`encoding`](#optionsencoding) option.344[More info.](docs/execution.md#synchronous-execution)345346#### $(file, arguments?, options?)347348`file`: `string | URL`\349`arguments`: `string[]`\350`options`: [`Options`](#options)\351_Returns_: [`Subprocess`](#subprocess)352341Same as [`execa()`](#execafile-arguments-options) but using the [`stdin: 'inherit'`](#optionsstdin) and [`preferLocal: true`](#optionspreferlocal) options.353Same as [`execa()`](#execafile-arguments-options) but using [script-friendly default options](docs/scripts.md#script-files).354343Just like `execa()`, this can use the [template string syntax](#execacommand) or [bind options](#execaoptions). It can also be [run synchronously](#execasyncfile-arguments-options) using `$.sync()` or `$.s()`.355Just like `execa()`, this can use the [template string syntax](docs/execution.md#template-string-syntax) or [bind options](docs/execution.md#globalshared-options). It can also be [run synchronously](#execasyncfile-arguments-options) using `$.sync()` or `$.s()`.356345This is the preferred method when executing multiple commands in a script file. For more information, please see [this page](docs/scripts.md).357This is the preferred method when executing multiple commands in a script file.358359[More info.](docs/scripts.md)360361#### execaNode(scriptPath, arguments?, options?)362363`scriptPath`: `string | URL`\364`arguments`: `string[]`\
2 unmodified lines
367368Same as [`execa()`](#execafile-arguments-options) but using the [`node: true`](#optionsnode) option.369Executes a Node.js file using `node scriptPath ...arguments`.370357Just like `execa()`, this can use the [template string syntax](#execacommand) or [bind options](#execaoptions).371Just like `execa()`, this can use the [template string syntax](docs/execution.md#template-string-syntax) or [bind options](docs/execution.md#globalshared-options).372373This is the preferred method when executing Node.js files.374375[More info.](docs/node.md)376377#### execaCommand(command, options?)378379`command`: `string`\380`options`: [`Options`](#options)\381_Returns_: [`Subprocess`](#subprocess)382367[`execa`](#execafile-arguments-options) with the [template string syntax](#execacommand) allows the `file` or the `arguments` to be user-defined (by injecting them with `${}`). However, if _both_ the `file` and the `arguments` are user-defined, _and_ those are supplied as a single string, then `execaCommand(command)` must be used instead.383Executes a command. `command` is a string that includes both the `file` and its `arguments`.384369This is only intended for very specific cases, such as a REPL. This should be avoided otherwise.385This is only intended for very specific cases, such as a [REPL](https://en.wikipedia.org/wiki/Read%E2%80%93eval%E2%80%93print_loop). This should be avoided otherwise.386371Just like `execa()`, this can [bind options](#execaoptions). It can also be [run synchronously](#execasyncfile-arguments-options) using `execaCommandSync()`.387Just like `execa()`, this can [bind options](docs/execution.md#globalshared-options). It can also be [run synchronously](#execasyncfile-arguments-options) using `execaCommandSync()`.388373Arguments are [automatically escaped](#shell-syntax). They can contain any character, but spaces must be escaped with a backslash like `execaCommand('echo has\\ space')`.389[More info.](docs/escaping.md#user-defined-input)390375### Shell syntax376377For all the [methods above](#methods), no shell interpreter (Bash, cmd.exe, etc.) is used unless the [`shell`](#optionsshell) option is set. This means shell-specific characters and expressions (`$variable`, `&&`, `||`, `;`, `|`, etc.) have no special meaning and do not need to be escaped.378391### subprocess392393The return value of all [asynchronous methods](#methods) is both:394- a `Promise` resolving or rejecting with a subprocess [`result`](#result).395- a [`child_process` instance](https://nodejs.org/api/child_process.html#child_process_class_childprocess) with the following methods and properties.396397[More info.](docs/execution.md#subprocess)398399#### subprocess.pipe(file, arguments?, options?)400401`file`: `string | URL`\402`arguments`: `string[]`\403`options`: [`Options`](#options) and [`PipeOptions`](#pipeoptions)\404_Returns_: [`Promise<Result>`](#result)405392[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](#result). If either subprocess is rejected, this is rejected with that subprocess' [error](#execaerror) instead.406[Pipe](https://nodejs.org/api/stream.html#readablepipedestination-options) the subprocess' [`stdout`](#subprocessstdout) to a second Execa subprocess' [`stdin`](#subprocessstdin). This resolves with that second subprocess' [result](#result). If either subprocess is rejected, this is rejected with that subprocess' [error](#execaerror) instead.407408This follows the same syntax as [`execa(file, arguments?, options?)`](#execafile-arguments-options) except both [regular options](#options) and [pipe-specific options](#pipeoptions) can be specified.409396This can be called multiple times to chain a series of subprocesses.410[More info.](docs/pipe.md#array-syntax)411398Multiple subprocesses can be piped to the same subprocess. Conversely, the same subprocess can be piped to multiple other subprocesses.399412#### subprocess.pipe\`command\`413#### subprocess.pipe(options)\`command\`414415`command`: `string`\416`options`: [`Options`](#options) and [`PipeOptions`](#pipeoptions)\417_Returns_: [`Promise<Result>`](#result)418407Like [`subprocess.pipe(file, arguments?, options?)`](#subprocesspipefile-arguments-options) but using a [`command` template string](docs/scripts.md#piping-stdout-to-another-command) instead. This follows the same syntax as `execa` [template strings](#execacommand).419Like [`subprocess.pipe(file, arguments?, options?)`](#subprocesspipefile-arguments-options) but using a [`command` template string](docs/scripts.md#piping-stdout-to-another-command) instead. This follows the same syntax as `execa` [template strings](docs/execution.md#template-string-syntax).420421[More info.](docs/pipe.md#template-string-syntax)422423#### subprocess.pipe(secondSubprocess, pipeOptions?)424425`secondSubprocess`: [`execa()` return value](#subprocess)\426`pipeOptions`: [`PipeOptions`](#pipeoptions)\427_Returns_: [`Promise<Result>`](#result)428415Like [`subprocess.pipe(file, arguments?, options?)`](#subprocesspipefile-arguments-options) but using the [return value](#subprocess) of another `execa()` call instead.429Like [`subprocess.pipe(file, arguments?, options?)`](#subprocesspipefile-arguments-options) but using the [return value](#subprocess) of another [`execa()`](#execafile-arguments-options) call instead.430417This is the most advanced method to pipe subprocesses. It is useful in specific cases, such as piping multiple subprocesses to the same subprocess.431[More info.](docs/pipe.md#advanced-syntax)432433##### pipeOptions434435Type: `object`
2 unmodified lines
438439Type: `"stdout" | "stderr" | "all" | "fd3" | "fd4" | ...`\440Default: `"stdout"`441428Which stream to pipe from the source subprocess. A file descriptor like `"fd3"` can also be passed.442Which stream to pipe from the source subprocess. A [file descriptor](https://en.wikipedia.org/wiki/File_descriptor) like `"fd3"` can also be passed.443430`"all"` pipes both `stdout` and `stderr`. This requires the [`all`](#optionsall) option to be `true`.444`"all"` pipes both [`stdout`](#subprocessstdout) and [`stderr`](#subprocessstderr). This requires the [`all`](#optionsall) option to be `true`.445446[More info.](docs/pipe.md#source-file-descriptor)447448##### pipeOptions.to449450Type: `"stdin" | "fd3" | "fd4" | ...`\451Default: `"stdin"`452437Which stream to pipe to the destination subprocess. A file descriptor like `"fd3"` can also be passed.453Which [stream](#subprocessstdin) to pipe to the destination subprocess. A [file descriptor](https://en.wikipedia.org/wiki/File_descriptor) like `"fd3"` can also be passed.454455[More info.](docs/pipe.md#destination-file-descriptor)456457##### pipeOptions.unpipeSignal458459Type: [`AbortSignal`](https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal)460461Unpipe the subprocess when the signal aborts.462445The [`subprocess.pipe()`](#subprocesspipefile-arguments-options) method will be rejected with a cancellation error.463[More info.](docs/pipe.md#unpipe)464465#### subprocess.kill(signal, error?)466#### subprocess.kill(error?)467
6 unmodified lines
474This returns `false` when the signal could not be sent, for example when the subprocess has already exited.475476When an error is passed as argument, it is set to the subprocess' [`error.cause`](#errorcause). 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).477460[More info.](https://nodejs.org/api/child_process.html#subprocesskillsignal)478[More info.](docs/termination.md)479480#### subprocess.pid481482_Type_: `number | undefined`
1 unmodified line
484Process identifier ([PID](https://en.wikipedia.org/wiki/Process_identifier)).485486This is `undefined` if the subprocess failed to spawn.487488[More info.](docs/termination.md#inter-process-termination)489490#### subprocess.send(message)491492`message`: `unknown`\493_Returns_: `boolean`
4 unmodified lines
498This returns `true` on success.499500This requires the [`ipc`](#optionsipc) option to be `true`.501482[More info.](https://nodejs.org/api/child_process.html#subprocesssendmessage-sendhandle-options-callback)502[More info.](docs/ipc.md#exchanging-messages)503504#### subprocess.on('message', (message) => void)505506`message`: `unknown`
2 unmodified lines
509The subprocess sends it using [`process.send(message)`](https://nodejs.org/api/process.html#processsendmessage-sendhandle-options-callback).510511This requires the [`ipc`](#optionsipc) option to be `true`.512493[More info.](https://nodejs.org/api/child_process.html#event-message)513[More info.](docs/ipc.md#exchanging-messages)514515#### subprocess.stdin516517Type: [`Writable | null`](https://nodejs.org/api/stream.html#class-streamwritable)518499The subprocess [`stdin`](#optionsstdin) as a stream.519The subprocess [`stdin`](https://en.wikipedia.org/wiki/Standard_streams#Standard_input_(stdin)) as a stream.520501This is `null` if the [`stdin`](#optionsstdin) option is set to `'inherit'`, `'ignore'`, `Readable` or `integer`.521This is `null` if the [`stdin`](#optionsstdin) option is set to [`'inherit'`](docs/input.md#terminal-input), [`'ignore'`](docs/input.md#ignore-input), [`Readable`](docs/streams.md#input) or [`integer`](docs/input.md#terminal-input).522503This is intended for advanced cases. Please consider using the [`stdin`](#optionsstdin) option, [`input`](#optionsinput) option, [`inputFile`](#optionsinputfile) option, or [`subprocess.pipe()`](#subprocesspipefile-arguments-options) instead.523[More info.](docs/streams.md#manual-streaming)524525#### subprocess.stdout526527Type: [`Readable | null`](https://nodejs.org/api/stream.html#class-streamreadable)528509The subprocess [`stdout`](#optionsstdout) as a stream.529The subprocess [`stdout`](https://en.wikipedia.org/wiki/Standard_streams#Standard_output_(stdout)) as a stream.530511This is `null` if the [`stdout`](#optionsstdout) option is set to `'inherit'`, `'ignore'`, `Writable` or `integer`.531This is `null` if the [`stdout`](#optionsstdout) option is set to [`'inherit'`](docs/output.md#terminal-output), [`'ignore'`](docs/output.md#ignore-output), [`Writable`](docs/streams.md#output) or [`integer`](docs/output.md#terminal-output), or if the [`buffer`](#optionsbuffer) option is `false`.532513This is intended for advanced cases. Please consider using [`result.stdout`](#resultstdout), the [`stdout`](#optionsstdout) option, [`subprocess.iterable()`](#subprocessiterablereadableoptions), or [`subprocess.pipe()`](#subprocesspipefile-arguments-options) instead.533[More info.](docs/streams.md#manual-streaming)534535#### subprocess.stderr536537Type: [`Readable | null`](https://nodejs.org/api/stream.html#class-streamreadable)538519The subprocess [`stderr`](#optionsstderr) as a stream.539The subprocess [`stderr`](https://en.wikipedia.org/wiki/Standard_streams#Standard_error_(stderr)) as a stream.540521This is `null` if the [`stderr`](#optionsstdout) option is set to `'inherit'`, `'ignore'`, `Writable` or `integer`.541This is `null` if the [`stderr`](#optionsstdout) option is set to [`'inherit'`](docs/output.md#terminal-output), [`'ignore'`](docs/output.md#ignore-output), [`Writable`](docs/streams.md#output) or [`integer`](docs/output.md#terminal-output), or if the [`buffer`](#optionsbuffer) option is `false`.542523This is intended for advanced cases. Please consider using [`result.stderr`](#resultstderr), the [`stderr`](#optionsstderr) option, [`subprocess.iterable()`](#subprocessiterablereadableoptions), or [`subprocess.pipe()`](#subprocesspipefile-arguments-options) instead.543[More info.](docs/streams.md#manual-streaming)544545#### subprocess.all546547Type: [`Readable | undefined`](https://nodejs.org/api/stream.html#class-streamreadable)548529Stream [combining/interleaving](#ensuring-all-output-is-interleaved) [`subprocess.stdout`](#subprocessstdout) and [`subprocess.stderr`](#subprocessstderr).549Stream combining/interleaving [`subprocess.stdout`](#subprocessstdout) and [`subprocess.stderr`](#subprocessstderr).550531This is `undefined` if either:532- the [`all`](#optionsall) option is `false` (the default value).533- both [`stdout`](#optionsstdout) and [`stderr`](#optionsstderr) options are set to `'inherit'`, `'ignore'`, `Writable` or `integer`.551This requires the [`all`](#optionsall) option to be `true`.552535This is intended for advanced cases. Please consider using [`result.all`](#resultall), the [`stdout`](#optionsstdout)/[`stderr`](#optionsstderr) option, [`subprocess.iterable()`](#subprocessiterablereadableoptions), or [`subprocess.pipe()`](#subprocesspipefile-arguments-options) instead.553This is `undefined` if [`stdout`](#optionsstdout) and [`stderr`](#optionsstderr) options are set to [`'inherit'`](docs/output.md#terminal-output), [`'ignore'`](docs/output.md#ignore-output), [`Writable`](docs/streams.md#output) or [`integer`](docs/output.md#terminal-output), or if the [`buffer`](#optionsbuffer) option is `false`.554555More info on [interleaving](docs/output.md#interleaved-output) and [streaming](docs/streams.md#manual-streaming).556557#### subprocess.stdio558559Type: [`[Writable | null, Readable | null, Readable | null, ...Array<Writable | Readable | null>]`](https://nodejs.org/api/stream.html#class-streamreadable)560541The subprocess `stdin`, `stdout`, `stderr` and [other files descriptors](#optionsstdio) as an array of streams.561The subprocess [`stdin`](#subprocessstdin), [`stdout`](#subprocessstdout), [`stderr`](#subprocessstderr) and [other files descriptors](#optionsstdio) as an array of streams.562543Each array item is `null` if the corresponding [`stdin`](#optionsstdin), [`stdout`](#optionsstdout), [`stderr`](#optionsstderr) or [`stdio`](#optionsstdio) option is set to `'inherit'`, `'ignore'`, `Stream` or `integer`.563Each array item is `null` if the corresponding [`stdin`](#optionsstdin), [`stdout`](#optionsstdout), [`stderr`](#optionsstderr) or [`stdio`](#optionsstdio) option is set to [`'inherit'`](docs/output.md#terminal-output), [`'ignore'`](docs/output.md#ignore-output), [`Stream`](docs/streams.md#output) or [`integer`](docs/output.md#terminal-output), or if the [`buffer`](#optionsbuffer) option is `false`.564545This is intended for advanced cases. Please consider using [`result.stdio`](#resultstdio), the [`stdio`](#optionsstdio) option, [`subprocess.iterable()`](#subprocessiterablereadableoptions) or [`subprocess.pipe()`](#subprocesspipefile-arguments-options) instead.565[More info.](docs/streams.md#manual-streaming)566567#### subprocess\[Symbol.asyncIterator\]()568549_Returns_: `AsyncIterable`569_Returns_: [`AsyncIterable`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#the_async_iterator_and_async_iterable_protocols)570571Subprocesses are [async iterables](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol/asyncIterator). They iterate over each output line.572553The iteration waits for the subprocess to end. It throws if the subprocess [fails](#result). This means you do not need to `await` the subprocess' [promise](#subprocess).573[More info.](docs/lines.md#progressive-splitting)574575#### subprocess.iterable(readableOptions?)576577`readableOptions`: [`ReadableOptions`](#readableoptions)\558_Returns_: `AsyncIterable`578_Returns_: [`AsyncIterable`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#the_async_iterator_and_async_iterable_protocols)579580Same as [`subprocess[Symbol.asyncIterator]`](#subprocesssymbolasynciterator) except [options](#readableoptions) can be provided.581582[More info.](docs/lines.md#progressive-splitting)583584#### subprocess.readable(readableOptions?)585586`readableOptions`: [`ReadableOptions`](#readableoptions)\587_Returns_: [`Readable`](https://nodejs.org/api/stream.html#class-streamreadable) Node.js stream588589Converts the subprocess to a readable stream.590569Unlike [`subprocess.stdout`](#subprocessstdout), the stream waits for the subprocess to end and emits an [`error`](https://nodejs.org/api/stream.html#event-error) event if the subprocess [fails](#result). This means you do not need to `await` the subprocess' [promise](#subprocess). On the other hand, you do need to handle to the stream `error` event. This can be done by using [`await finished(stream)`](https://nodejs.org/api/stream.html#streamfinishedstream-options), [`await pipeline(..., stream)`](https://nodejs.org/api/stream.html#streampipelinesource-transforms-destination-options) or [`await text(stream)`](https://nodejs.org/api/webstreams.html#streamconsumerstextstream) which throw an exception when the stream errors.591[More info.](docs/streams.md#converting-a-subprocess-to-a-stream)592571Before using this method, please first consider the [`stdin`](#optionsstdin)/[`stdout`](#optionsstdout)/[`stderr`](#optionsstderr)/[`stdio`](#optionsstdio) options, [`subprocess.pipe()`](#subprocesspipefile-arguments-options) or [`subprocess.iterable()`](#subprocessiterablereadableoptions).572593#### subprocess.writable(writableOptions?)594595`writableOptions`: [`WritableOptions`](#writableoptions)\596_Returns_: [`Writable`](https://nodejs.org/api/stream.html#class-streamwritable) Node.js stream597598Converts the subprocess to a writable stream.599580Unlike [`subprocess.stdin`](#subprocessstdin), the stream waits for the subprocess to end and emits an [`error`](https://nodejs.org/api/stream.html#event-error) event if the subprocess [fails](#result). This means you do not need to `await` the subprocess' [promise](#subprocess). On the other hand, you do need to handle to the stream `error` event. This can be done by using [`await finished(stream)`](https://nodejs.org/api/stream.html#streamfinishedstream-options) or [`await pipeline(stream, ...)`](https://nodejs.org/api/stream.html#streampipelinesource-transforms-destination-options) which throw an exception when the stream errors.600[More info.](docs/streams.md#converting-a-subprocess-to-a-stream)601582Before using this method, please first consider the [`stdin`](#optionsstdin)/[`stdout`](#optionsstdout)/[`stderr`](#optionsstderr)/[`stdio`](#optionsstdio) options or [`subprocess.pipe()`](#subprocesspipefile-arguments-options).583602#### subprocess.duplex(duplexOptions?)603604`duplexOptions`: [`ReadableOptions | WritableOptions`](#readableoptions)\605_Returns_: [`Duplex`](https://nodejs.org/api/stream.html#class-streamduplex) Node.js stream606607Converts the subprocess to a duplex stream.608591The stream waits for the subprocess to end and emits an [`error`](https://nodejs.org/api/stream.html#event-error) event if the subprocess [fails](#result). This means you do not need to `await` the subprocess' [promise](#subprocess). On the other hand, you do need to handle to the stream `error` event. This can be done by using [`await finished(stream)`](https://nodejs.org/api/stream.html#streamfinishedstream-options), [`await pipeline(..., stream, ...)`](https://nodejs.org/api/stream.html#streampipelinesource-transforms-destination-options) or [`await text(stream)`](https://nodejs.org/api/webstreams.html#streamconsumerstextstream) which throw an exception when the stream errors.609[More info.](docs/streams.md#converting-a-subprocess-to-a-stream)610593Before using this method, please first consider the [`stdin`](#optionsstdin)/[`stdout`](#optionsstdout)/[`stderr`](#optionsstderr)/[`stdio`](#optionsstdio) options, [`subprocess.pipe()`](#subprocesspipefile-arguments-options) or [`subprocess.iterable()`](#subprocessiterablereadableoptions).594611##### readableOptions612613Type: `object`614
1 unmodified line
616617Type: `"stdout" | "stderr" | "all" | "fd3" | "fd4" | ...`\618Default: `"stdout"`619604Which stream to read from the subprocess. A file descriptor like `"fd3"` can also be passed.620Which stream to read from the subprocess. A [file descriptor](https://en.wikipedia.org/wiki/File_descriptor) like `"fd3"` can also be passed.621606`"all"` reads both `stdout` and `stderr`. This requires the [`all`](#optionsall) option to be `true`.622`"all"` reads both [`stdout`](#subprocessstdout) and [`stderr`](#subprocessstderr). This requires the [`all`](#optionsall) option to be `true`.623624[More info.](docs/streams.md#different-file-descriptor)625626##### readableOptions.binary627628Type: `boolean`\629Default: `false` with [`subprocess.iterable()`](#subprocessiterablereadableoptions), `true` with [`subprocess.readable()`](#subprocessreadablereadableoptions)/[`subprocess.duplex()`](#subprocessduplexduplexoptions)630613If `false`, the stream iterates over lines. Each line is a string. Also, the stream is in [object mode](https://nodejs.org/api/stream.html#object-mode).631If `false`, iterates over lines. Each line is a string.632615If `true`, the stream iterates over arbitrary chunks of data. Each line is an `Uint8Array` (with [`subprocess.iterable()`](#subprocessiterablereadableoptions)) or a [`Buffer`](https://nodejs.org/api/buffer.html#class-buffer) (otherwise).633If `true`, iterates over arbitrary chunks of data. Each line is an [`Uint8Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array) (with [`subprocess.iterable()`](#subprocessiterablereadableoptions)) or a [`Buffer`](https://nodejs.org/api/buffer.html#class-buffer) (with [`subprocess.readable()`](#subprocessreadablereadableoptions)/[`subprocess.duplex()`](#subprocessduplexduplexoptions)).634635This is always `true` when the [`encoding`](#optionsencoding) option is binary.636637More info for [iterables](docs/binary.md#iterable) and [streams](docs/binary.md#streams).638639##### readableOptions.preserveNewlines640641Type: `boolean`\642Default: `false` with [`subprocess.iterable()`](#subprocessiterablereadableoptions), `true` with [`subprocess.readable()`](#subprocessreadablereadableoptions)/[`subprocess.duplex()`](#subprocessduplexduplexoptions)643624If both this option and the [`binary`](#readableoptionsbinary) option is `false`, newlines are stripped from each line.644If both this option and the [`binary`](#readableoptionsbinary) option is `false`, [newlines](https://en.wikipedia.org/wiki/Newline) are stripped from each line.645646[More info.](docs/lines.md#iterable)647648##### writableOptions649650Type: `object`651
1 unmodified line
653654Type: `"stdin" | "fd3" | "fd4" | ...`\655Default: `"stdin"`656635Which stream to write to the subprocess. A file descriptor like `"fd3"` can also be passed.657Which [stream](#subprocessstdin) to write to the subprocess. A [file descriptor](https://en.wikipedia.org/wiki/File_descriptor) like `"fd3"` can also be passed.658659[More info.](docs/streams.md#different-file-descriptor)660661### Result662663Type: `object`664641Result of a subprocess execution.665[Result](docs/execution.md#result) of a subprocess execution.666643When the subprocess [fails](#resultfailed), it is rejected with an [`ExecaError`](#execaerror) instead.667When the subprocess [fails](docs/errors.md#subprocess-failure), it is rejected with an [`ExecaError`](#execaerror) instead.668669#### result.command670671Type: `string`672649The file and arguments that were run, for logging purposes.673The file and [arguments](docs/input.md#command-arguments) that were run.674651This is not escaped and should not be executed directly as a subprocess, including using [`execa()`](#execafile-arguments-options) or [`execaCommand()`](#execacommandcommand-options).675[More info.](docs/debugging.md#command)676677#### result.escapedCommand678679Type: `string`680681Same as [`command`](#resultcommand) but escaped.682659Unlike `command`, control characters are escaped, which makes it safe to print in a terminal.683[More info.](docs/debugging.md#command)684661This can also be copied and pasted into a shell, for debugging purposes.662Since the escaping is fairly basic, this should not be executed directly as a subprocess, including using [`execa()`](#execafile-arguments-options) or [`execaCommand()`](#execacommandcommand-options).663685#### result.cwd686687Type: `string`688689The [current directory](#optionscwd) in which the command was run.690691[More info.](docs/environment.md#current-directory)692693#### result.durationMs694695Type: `number`696697Duration of the subprocess, in milliseconds.698699[More info.](docs/debugging.md#duration)700701#### result.stdout702703Type: `string | Uint8Array | string[] | Uint8Array[] | unknown[] | undefined`704680The output of the subprocess on `stdout`.705The output of the subprocess on [`stdout`](https://en.wikipedia.org/wiki/Standard_streams#Standard_output_(stdout)).706682This is `undefined` if the [`stdout`](#optionsstdout) option is set to only `'inherit'`, `'ignore'`, `Writable` or `integer`. This is an array if the [`lines`](#optionslines) option is `true`, or if the `stdout` option is a [transform in object mode](docs/transform.md#object-mode).707This is `undefined` if the [`stdout`](#optionsstdout) option is set to only [`'inherit'`](docs/output.md#terminal-output), [`'ignore'`](docs/output.md#ignore-output), [`Writable`](docs/streams.md#output) or [`integer`](docs/output.md#terminal-output), or if the [`buffer`](#optionsbuffer) option is `false`.708709This is an array if the [`lines`](#optionslines) option is `true`, or if the `stdout` option is a [transform in object mode](docs/transform.md#object-mode).710711[More info.](docs/output.md#stdout-and-stderr)712713#### result.stderr714715Type: `string | Uint8Array | string[] | Uint8Array[] | unknown[] | undefined`716688The output of the subprocess on `stderr`.717The output of the subprocess on [`stderr`](https://en.wikipedia.org/wiki/Standard_streams#Standard_error_(stderr)).718690This is `undefined` if the [`stderr`](#optionsstderr) option is set to only `'inherit'`, `'ignore'`, `Writable` or `integer`. This is an array if the [`lines`](#optionslines) option is `true`, or if the `stderr` option is a [transform in object mode](docs/transform.md#object-mode).719This is `undefined` if the [`stderr`](#optionsstderr) option is set to only [`'inherit'`](docs/output.md#terminal-output), [`'ignore'`](docs/output.md#ignore-output), [`Writable`](docs/streams.md#output) or [`integer`](docs/output.md#terminal-output), or if the [`buffer`](#optionsbuffer) option is `false`.720721This is an array if the [`lines`](#optionslines) option is `true`, or if the `stderr` option is a [transform in object mode](docs/transform.md#object-mode).722723[More info.](docs/output.md#stdout-and-stderr)724725#### result.all726727Type: `string | Uint8Array | string[] | Uint8Array[] | unknown[] | undefined`728696The output of the subprocess with [`result.stdout`](#resultstdout) and [`result.stderr`](#resultstderr) [interleaved](#ensuring-all-output-is-interleaved).729The output of the subprocess with [`result.stdout`](#resultstdout) and [`result.stderr`](#resultstderr) interleaved.730698This is `undefined` if either:699- the [`all`](#optionsall) option is `false` (the default value).700- both [`stdout`](#optionsstdout) and [`stderr`](#optionsstderr) options are set to only `'inherit'`, `'ignore'`, `Writable` or `integer`.731This requires the [`all`](#optionsall) option to be `true`.732733This is `undefined` if both [`stdout`](#optionsstdout) and [`stderr`](#optionsstderr) options are set to only [`'inherit'`](docs/output.md#terminal-output), [`'ignore'`](docs/output.md#ignore-output), [`Writable`](docs/streams.md#output) or [`integer`](docs/output.md#terminal-output), or if the [`buffer`](#optionsbuffer) option is `false`.734735This is an array if the [`lines`](#optionslines) option is `true`, or if either the `stdout` or `stderr` option is a [transform in object mode](docs/transform.md#object-mode).736737[More info.](docs/output.md#interleaved-output)738739#### result.stdio740741Type: `Array<string | Uint8Array | string[] | Uint8Array[] | unknown[] | undefined>`742743The output of the subprocess on [`stdin`](#optionsstdin), [`stdout`](#optionsstdout), [`stderr`](#optionsstderr) and [other file descriptors](#optionsstdio).744710Items are `undefined` when their corresponding [`stdio`](#optionsstdio) option is set to `'inherit'`, `'ignore'`, `Writable` or `integer`. Items are arrays when their corresponding `stdio` option is a [transform in object mode](docs/transform.md#object-mode).745Items are `undefined` when their corresponding [`stdio`](#optionsstdio) option is set to [`'inherit'`](docs/output.md#terminal-output), [`'ignore'`](docs/output.md#ignore-output), [`Writable`](docs/streams.md#output) or [`integer`](docs/output.md#terminal-output), or if the [`buffer`](#optionsbuffer) option is `false`.746747Items are arrays when their corresponding `stdio` option is a [transform in object mode](docs/transform.md#object-mode).748749[More info.](docs/output.md#additional-file-descriptors)750751#### result.failed752753Type: `boolean`754755Whether the subprocess failed to run.756757[More info.](docs/errors.md#subprocess-failure)758759#### result.timedOut760761Type: `boolean`762722Whether the subprocess timed out.763Whether the subprocess timed out due to the [`timeout`](#optionstimeout) option.764765[More info.](docs/termination.md#timeout)766767#### result.isCanceled768769Type: `boolean`770771Whether the subprocess was canceled using the [`cancelSignal`](#optionscancelsignal) option.772773[More info.](docs/termination.md#canceling)774775#### result.isTerminated776777Type: `boolean`778734Whether the subprocess was terminated by a signal (like `SIGTERM`) sent by either:779Whether the subprocess was terminated by a [signal](docs/termination.md#signal-termination) (like [`SIGTERM`](docs/termination.md#sigterm)) sent by either:780- The current process.736- Another process. This case is [not supported on Windows](https://nodejs.org/api/process.html#signal-events).781- [Another process](docs/termination.md#inter-process-termination). This case is [not supported on Windows](https://nodejs.org/api/process.html#signal-events).782783[More info.](docs/termination.md#signal-name-and-description)784785#### result.isMaxBuffer786787Type: `boolean`788789Whether the subprocess failed because its output was larger than the [`maxBuffer`](#optionsmaxbuffer) option.790791[More info.](docs/output.md#big-output)792793#### result.exitCode794795Type: `number | undefined`796748The numeric exit code of the subprocess that was run.797The numeric [exit code](https://en.wikipedia.org/wiki/Exit_status) of the subprocess that was run.798799This is `undefined` when the subprocess could not be spawned or was terminated by a [signal](#resultsignal).800801[More info.](docs/errors.md#exit-code)802803#### result.signal804805Type: `string | undefined`806756The name of the signal (like `SIGTERM`) that terminated the subprocess, sent by either:807The name of the [signal](docs/termination.md#signal-termination) (like [`SIGTERM`](docs/termination.md#sigterm)) that terminated the subprocess, sent by either:808- The current process.758- Another process. This case is [not supported on Windows](https://nodejs.org/api/process.html#signal-events).809- [Another process](docs/termination.md#inter-process-termination). This case is [not supported on Windows](https://nodejs.org/api/process.html#signal-events).810760If a signal terminated the subprocess, this property is defined and included in the error message. Otherwise it is `undefined`.811If a signal terminated the subprocess, this property is defined and included in the [error message](#errormessage). Otherwise it is `undefined`.812813[More info.](docs/termination.md#signal-name-and-description)814815#### result.signalDescription816817Type: `string | undefined`818766A human-friendly description of the signal that was used to terminate the subprocess. For example, `Floating point arithmetic error`.819A human-friendly description of the [signal](docs/termination.md#signal-termination) that was used to terminate the subprocess.820821If 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.822823[More info.](docs/termination.md#signal-name-and-description)824825#### result.pipedFrom826827Type: [`Array<Result | ExecaError>`](#result)828774Results 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.829[Results](#result) of the other subprocesses that were [piped](#pipe-multiple-subprocesses) into this subprocess.830831This array is initially empty and is populated each time the [`subprocess.pipe()`](#subprocesspipefile-arguments-options) method resolves.832833[More info.](docs/pipe.md#errors)834835### ExecaError836### ExecaSyncError837838Type: `Error`839783Exception thrown when the subprocess [fails](#resultfailed), either:784- its [exit code](#resultexitcode) is not `0`785- it was [terminated](#resultisterminated) with a [signal](#resultsignal), including [`subprocess.kill()`](#subprocesskillerror)786- [timing out](#resulttimedout)787- [being canceled](#resultiscanceled)788- there's not enough memory or there are already too many subprocesses840Exception thrown when the subprocess [fails](docs/errors.md#subprocess-failure).841842This has the same shape as [successful results](#result), with the following additional properties.843844[More info.](docs/errors.md)845846#### error.message847848Type: `string`849796Error message when the subprocess failed to run. In addition to the [underlying error message](#errororiginalmessage), it also contains some information related to why the subprocess errored.850Error message when the subprocess [failed](docs/errors.md#subprocess-failure) to run.851798The subprocess [`stderr`](#resultstderr), [`stdout`](#resultstdout) and other [file descriptors' output](#resultstdio) are appended to the end, separated with newlines and not interleaved.852[More info.](docs/errors.md#error-message)853854#### error.shortMessage855856Type: `string`857804This is the same as the [`message` property](#errormessage) except it does not include the subprocess [`stdout`](#resultstdout)/[`stderr`](#resultstderr)/[`stdio`](#resultstdio).858This is the same as [`error.message`](#errormessage) except it does not include the subprocess [output](docs/output.md).859860[More info.](docs/errors.md#error-message)861862#### error.originalMessage863864Type: `string | undefined`865810Original error message. This is the same as the `message` property excluding the subprocess [`stdout`](#resultstdout)/[`stderr`](#resultstderr)/[`stdio`](#resultstdio) and some additional information added by Execa.866Original error message. This is the same as [`error.message`](#errormessage) excluding the subprocess [output](docs/output.md) and some additional information added by Execa.867812This exists only if the subprocess exited due to an `error` event or a timeout.868[More info.](docs/errors.md#error-message)869870#### error.cause871872Type: `unknown | undefined`
1 unmodified line
874Underlying error, if there is one. For example, this is set by [`subprocess.kill(error)`](#subprocesskillerror).875876This is usually an `Error` instance.877878[More info.](docs/termination.md#error-message-and-stack-trace)879880#### error.code881882Type: `string | undefined`883
4 unmodified lines
888Type: `object`889890This lists all options for [`execa()`](#execafile-arguments-options) and the [other methods](#methods).891834Some options are related to the subprocess output: [`verbose`](#optionsverbose), [`lines`](#optionslines), [`stripFinalNewline`](#optionsstripfinalnewline), [`buffer`](#optionsbuffer), [`maxBuffer`](#optionsmaxbuffer). By default, those options apply to all file descriptors (`stdout`, `stderr`, etc.). A plain object can be passed instead to apply them to only `stdout`, `stderr`, `fd3`, etc.892The following options [can specify different values](docs/output.md#stdoutstderr-specific-options) for [`stdout`](#optionsstdout) and [`stderr`](#optionsstderr): [`verbose`](#optionsverbose), [`lines`](#optionslines), [`stripFinalNewline`](#optionsstripfinalnewline), [`buffer`](#optionsbuffer), [`maxBuffer`](#optionsmaxbuffer).893836```js837await execa('./run.js', {verbose: 'full'}) // Same value for stdout and stderr838await execa('./run.js', {verbose: {stdout: 'none', stderr: 'full'}}) // Different values839```840894#### options.reject895896Type: `boolean`\897Default: `true`898846Setting this to `false` resolves the promise with the [error](#execaerror) instead of rejecting it.899Setting this to `false` resolves the [result's promise](#subprocess) with the [error](#execaerror) instead of rejecting it.900901[More info.](docs/errors.md#preventing-exceptions)902903#### options.shell904905Type: `boolean | string | URL`\906Default: `false`907853If `true`, runs `file` inside of a shell. Uses `/bin/sh` on UNIX and `cmd.exe` on Windows. A different shell can be specified as a string. The shell should understand the `-c` switch on UNIX or `/d /s /c` on Windows.908If `true`, runs the command inside of a [shell](https://en.wikipedia.org/wiki/Shell_(computing)).909855We recommend against using this option since it is:856- not cross-platform, encouraging shell-specific syntax.857- slower, because of the additional shell interpretation.858- unsafe, potentially allowing command injection.910Uses [`/bin/sh`](https://en.wikipedia.org/wiki/Unix_shell) on UNIX and [`cmd.exe`](https://en.wikipedia.org/wiki/Cmd.exe) on Windows. A different shell can be specified as a string. The shell should understand the `-c` switch on UNIX or `/d /s /c` on Windows.911912We [recommend against](docs/shell.md#avoiding-shells) using this option.913914[More info.](docs/shell.md)915916#### options.cwd917918Type: `string | URL`\919Default: `process.cwd()`920865Current working directory of the subprocess.921Current [working directory](https://en.wikipedia.org/wiki/Working_directory) of the subprocess.922923This is also used to resolve the [`nodePath`](#optionsnodepath) option when it is a relative path.924925[More info.](docs/environment.md#current-directory)926927#### options.env928929Type: `object`\872Default: `process.env`930Default: [`process.env`](https://nodejs.org/api/process.html#processenv)931874Environment key-value pairs.932[Environment variables](https://en.wikipedia.org/wiki/Environment_variable).933934Unless the [`extendEnv`](#optionsextendenv) option is `false`, the subprocess also uses the current process' environment variables ([`process.env`](https://nodejs.org/api/process.html#processenv)).935936[More info.](docs/input.md#environment-variables)937938#### options.extendEnv939940Type: `boolean`\941Default: `true`942943If `true`, the subprocess uses both the [`env`](#optionsenv) option and the current process' environment variables ([`process.env`](https://nodejs.org/api/process.html#processenv)).944If `false`, only the `env` option is used, not `process.env`.945946[More info.](docs/input.md#environment-variables)947948#### options.preferLocal949950Type: `boolean`\951Default: `true` with [`$`](#file-arguments-options), `false` otherwise952891Prefer locally installed binaries when looking for a binary to execute.\892If you `$ npm install foo`, you can then `execa('foo')`.953Prefer locally installed binaries when looking for a binary to execute.954955[More info.](docs/environment.md#local-binaries)956957#### options.localDir958959Type: `string | URL`\897Default: `process.cwd()`960Default: [`cwd`](#optionscwd) option961899Preferred path to find locally installed binaries in (use with `preferLocal`).962Preferred path to find locally installed binaries, when using the [`preferLocal`](#optionspreferlocal) option.963964[More info.](docs/environment.md#local-binaries)965966#### options.node967968Type: `boolean`\969Default: `true` with [`execaNode()`](#execanodescriptpath-arguments-options), `false` otherwise970971If `true`, runs with Node.js. The first argument must be a Node.js file.972973[More info.](docs/node.md)974975#### options.nodeOptions976977Type: `string[]`\978Default: [`process.execArgv`](https://nodejs.org/api/process.html#process_process_execargv) (current Node.js CLI options)979913List of [CLI options](https://nodejs.org/api/cli.html#cli_options) passed to the [Node.js executable](#optionsnodepath).980List of [CLI flags](https://nodejs.org/api/cli.html#cli_options) passed to the [Node.js executable](#optionsnodepath).981982Requires the [`node`](#optionsnode) option to be `true`.983984[More info.](docs/node.md#nodejs-cli-flags)985986#### options.nodePath987988Type: `string | URL`\989Default: [`process.execPath`](https://nodejs.org/api/process.html#process_process_execpath) (current Node.js executable)990991Path to the Node.js executable.992924For example, this can be used together with [`get-node`](https://github.com/ehmicky/get-node) to run a specific Node.js version.925993Requires the [`node`](#optionsnode) option to be `true`.994995[More info.](docs/node.md#nodejs-version)996997#### options.verbose998999Type: `'none' | 'short' | 'full'`\1000Default: `'none'`1001933If `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.1002If `verbose` is `'short'`, prints the command on [`stderr`](https://en.wikipedia.org/wiki/Standard_streams#Standard_error_(stderr)): its file, arguments, duration and (if it failed) error message.1003935If `verbose` is `'full'`, the command's `stdout` and `stderr` are printed too, unless either:936- the [`stdout`](#optionsstdout)/[`stderr`](#optionsstderr) option is `ignore` or `inherit`.937- the `stdout`/`stderr` is redirected to [a stream](https://nodejs.org/api/stream.html#readablepipedestination-options), [a file](#optionsstdout), a file descriptor, or [another subprocess](#subprocesspipefile-arguments-options).938- the [`encoding`](#optionsencoding) option is binary.1004If `verbose` is `'full'`, the command's [`stdout`](https://en.wikipedia.org/wiki/Standard_streams#Standard_output_(stdout)) and `stderr` are also printed.1005940This can also be set to `'full'` by setting the `NODE_DEBUG=execa` environment variable in the current process.1006By default, this applies to both `stdout` and `stderr`, but [different values can also be passed](docs/output.md#stdoutstderr-specific-options).1007942By default, this applies to both `stdout` and `stderr`, but [different values can also be passed](#options).1008[More info.](docs/debugging.md#verbose-mode)10091010#### options.buffer10111012Type: `boolean`\1013Default: `true`1014949Whether to return the subprocess' output using the [`result.stdout`](#resultstdout), [`result.stderr`](#resultstderr), [`result.all`](#resultall) and [`result.stdio`](#resultstdio) properties.1015When `buffer` is `false`, the [`result.stdout`](#resultstdout), [`result.stderr`](#resultstderr), [`result.all`](#resultall) and [`result.stdio`](#resultstdio) properties are not set.1016951On failure, the [`error.stdout`](#resultstdout), [`error.stderr`](#resultstderr), [`error.all`](#resultall) and [`error.stdio`](#resultstdio) properties are used instead.1017By default, this applies to both `stdout` and `stderr`, but [different values can also be passed](docs/output.md#stdoutstderr-specific-options).1018953When `buffer` is `false`, the output can still be read using the [`subprocess.stdout`](#subprocessstdout), [`subprocess.stderr`](#subprocessstderr), [`subprocess.stdio`](#subprocessstdio) and [`subprocess.all`](#subprocessall) streams. If the output is read, this should be done right away to avoid missing any data.1019[More info.](docs/output.md#low-memory)1020955By default, this applies to both `stdout` and `stderr`, but [different values can also be passed](#options).9561021#### options.input10221023Type: `string | Uint8Array | stream.Readable`1024961Write some input to the subprocess' `stdin`.1025Write some input to the subprocess' [`stdin`](https://en.wikipedia.org/wiki/Standard_streams#Standard_input_(stdin)).10261027See also the [`inputFile`](#optionsinputfile) and [`stdin`](#optionsstdin) options.10281029[More info.](docs/input.md#string-input)10301031#### options.inputFile10321033Type: `string | URL`1034969Use a file as input to the subprocess' `stdin`.1035Use a file as input to the subprocess' [`stdin`](https://en.wikipedia.org/wiki/Standard_streams#Standard_input_(stdin)).10361037See also the [`input`](#optionsinput) and [`stdin`](#optionsstdin) options.10381039[More info.](docs/input.md#file-input)10401041#### options.stdin10421043Type: `string | number | stream.Readable | ReadableStream | TransformStream | URL | {file: string} | Uint8Array | Iterable<string | Uint8Array | unknown> | AsyncIterable<string | Uint8Array | unknown> | GeneratorFunction<string | Uint8Array | unknown> | AsyncGeneratorFunction<string | Uint8Array | unknown> | {transform: GeneratorFunction | AsyncGeneratorFunction | Duplex | TransformStream}` (or a tuple of those types)\976Default: `inherit` with [`$`](#file-arguments-options), `pipe` otherwise1044Default: `'inherit'` with [`$`](#file-arguments-options), `'pipe'` otherwise1045978How to setup the subprocess' standard input. This can be:979- `'pipe'`: Sets [`subprocess.stdin`](#subprocessstdin) stream.980- `'overlapped'`: Like `'pipe'` but asynchronous on Windows.981- `'ignore'`: Do not use `stdin`.982- `'inherit'`: Re-use the current process' `stdin`.983- an integer: Re-use a specific file descriptor from the current process.984- a [Node.js `Readable` stream](#redirect-a-nodejs-stream-fromto-stdinstdoutstderr).985- `{ file: 'path' }` object.986- a file URL.987- a web [`ReadableStream`](https://developer.mozilla.org/en-US/docs/Web/API/ReadableStream).988- an [`Iterable`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#the_iterable_protocol) or an [`AsyncIterable`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#the_async_iterator_and_async_iterable_protocols)989- an `Uint8Array`.1046How to setup the subprocess' [standard input](https://en.wikipedia.org/wiki/Standard_streams#Standard_input_(stdin)). This can be [`'pipe'`](docs/streams.md#manual-streaming), [`'overlapped'`](docs/windows.md#asynchronous-io), [`'ignore`](docs/input.md#ignore-input), [`'inherit'`](docs/input.md#terminal-input), a [file descriptor integer](docs/input.md#terminal-input), a [Node.js `Readable` stream](docs/streams.md#input), a web [`ReadableStream`](docs/streams.md#web-streams), a [`{ file: 'path' }` object](docs/input.md#file-input), a [file URL](docs/input.md#file-input), an [`Iterable`](docs/streams.md#iterables-as-input) (including an [array of strings](docs/input.md#string-input)), an [`AsyncIterable`](docs/streams.md#iterables-as-input), an [`Uint8Array`](docs/binary.md#binary-input), a [generator function](docs/transform.md), a [`Duplex`](docs/transform.md#duplextransform-streams) or a web [`TransformStream`](docs/transform.md#duplextransform-streams).1047991This can be an [array of values](#redirect-stdinstdoutstderr-to-multiple-destinations) such as `['inherit', 'pipe']` or `[filePath, 'pipe']`.1048This can be an [array of values](docs/output.md#multiple-targets) such as `['inherit', 'pipe']` or `[fileUrl, 'pipe']`.1049993This can also be a generator function, a [`Duplex`](docs/transform.md#duplextransform-streams) or a web [`TransformStream`](docs/transform.md#duplextransform-streams) to transform the input. [Learn more.](docs/transform.md)1050More info on [available values](docs/input.md), [streaming](docs/streams.md) and [transforms](docs/transform.md).1051995[More info.](https://nodejs.org/api/child_process.html#child_process_options_stdio)9961052#### options.stdout10531054Type: `string | number | stream.Writable | WritableStream | TransformStream | URL | {file: string} | GeneratorFunction<string | Uint8Array | unknown> | AsyncGeneratorFunction<string | Uint8Array | unknown> | {transform: GeneratorFunction | AsyncGeneratorFunction | Duplex | TransformStream}` (or a tuple of those types)\1055Default: `pipe`10561002How to setup the subprocess' standard output. This can be:1003- `'pipe'`: Sets [`result.stdout`](#resultstdout) (as a string or `Uint8Array`) and [`subprocess.stdout`](#subprocessstdout) (as a stream).1004- `'overlapped'`: Like `'pipe'` but asynchronous on Windows.1005- `'ignore'`: Do not use `stdout`.1006- `'inherit'`: Re-use the current process' `stdout`.1007- an integer: Re-use a specific file descriptor from the current process.1008- a [Node.js `Writable` stream](#redirect-a-nodejs-stream-fromto-stdinstdoutstderr).1009- `{ file: 'path' }` object.1010- a file URL.1011- a web [`WritableStream`](https://developer.mozilla.org/en-US/docs/Web/API/WritableStream).1057How to setup the subprocess' [standard output](https://en.wikipedia.org/wiki/Standard_streams#Standard_input_(stdin)). This can be [`'pipe'`](docs/output.md#stdout-and-stderr), [`'overlapped'`](docs/windows.md#asynchronous-io), [`'ignore`](docs/output.md#ignore-output), [`'inherit'`](docs/output.md#terminal-output), a [file descriptor integer](docs/output.md#terminal-output), a [Node.js `Writable` stream](docs/streams.md#output), a web [`WritableStream`](docs/streams.md#web-streams), a [`{ file: 'path' }` object](docs/output.md#file-output), a [file URL](docs/output.md#file-output), a [generator function](docs/transform.md), a [`Duplex`](docs/transform.md#duplextransform-streams) or a web [`TransformStream`](docs/transform.md#duplextransform-streams).10581013This can be an [array of values](#redirect-stdinstdoutstderr-to-multiple-destinations) such as `['inherit', 'pipe']` or `[filePath, 'pipe']`.1059This can be an [array of values](docs/output.md#multiple-targets) such as `['inherit', 'pipe']` or `[fileUrl, 'pipe']`.10601015This can also be a generator function, a [`Duplex`](docs/transform.md#duplextransform-streams) or a web [`TransformStream`](docs/transform.md#duplextransform-streams) to transform the output. [Learn more.](docs/transform.md)1061More info on [available values](docs/output.md), [streaming](docs/streams.md) and [transforms](docs/transform.md).10621017[More info.](https://nodejs.org/api/child_process.html#child_process_options_stdio)10181063#### options.stderr10641065Type: `string | number | stream.Writable | WritableStream | TransformStream | URL | {file: string} | GeneratorFunction<string | Uint8Array | unknown> | AsyncGeneratorFunction<string | Uint8Array | unknown> | {transform: GeneratorFunction | AsyncGeneratorFunction | Duplex | TransformStream}` (or a tuple of those types)\1066Default: `pipe`10671024How to setup the subprocess' standard error. This can be:1025- `'pipe'`: Sets [`result.stderr`](#resultstderr) (as a string or `Uint8Array`) and [`subprocess.stderr`](#subprocessstderr) (as a stream).1026- `'overlapped'`: Like `'pipe'` but asynchronous on Windows.1027- `'ignore'`: Do not use `stderr`.1028- `'inherit'`: Re-use the current process' `stderr`.1029- an integer: Re-use a specific file descriptor from the current process.1030- a [Node.js `Writable` stream](#redirect-a-nodejs-stream-fromto-stdinstdoutstderr).1031- `{ file: 'path' }` object.1032- a file URL.1033- a web [`WritableStream`](https://developer.mozilla.org/en-US/docs/Web/API/WritableStream).1068How to setup the subprocess' [standard error](https://en.wikipedia.org/wiki/Standard_streams#Standard_input_(stdin)). This can be [`'pipe'`](docs/output.md#stdout-and-stderr), [`'overlapped'`](docs/windows.md#asynchronous-io), [`'ignore`](docs/output.md#ignore-output), [`'inherit'`](docs/output.md#terminal-output), a [file descriptor integer](docs/output.md#terminal-output), a [Node.js `Writable` stream](docs/streams.md#output), a web [`WritableStream`](docs/streams.md#web-streams), a [`{ file: 'path' }` object](docs/output.md#file-output), a [file URL](docs/output.md#file-output), a [generator function](docs/transform.md), a [`Duplex`](docs/transform.md#duplextransform-streams) or a web [`TransformStream`](docs/transform.md#duplextransform-streams).10691035This can be an [array of values](#redirect-stdinstdoutstderr-to-multiple-destinations) such as `['inherit', 'pipe']` or `[filePath, 'pipe']`.1070This can be an [array of values](docs/output.md#multiple-targets) such as `['inherit', 'pipe']` or `[fileUrl, 'pipe']`.10711037This can also be a generator function, a [`Duplex`](docs/transform.md#duplextransform-streams) or a web [`TransformStream`](docs/transform.md#duplextransform-streams) to transform the output. [Learn more.](docs/transform.md)1072More info on [available values](docs/output.md), [streaming](docs/streams.md) and [transforms](docs/transform.md).10731039[More info.](https://nodejs.org/api/child_process.html#child_process_options_stdio)10401074#### options.stdio10751076Type: `string | Array<string | number | stream.Readable | stream.Writable | ReadableStream | WritableStream | TransformStream | URL | {file: string} | Uint8Array | Iterable<string> | Iterable<Uint8Array> | Iterable<unknown> | AsyncIterable<string | Uint8Array | unknown> | GeneratorFunction<string | Uint8Array | unknown> | AsyncGeneratorFunction<string | Uint8Array | unknown> | {transform: GeneratorFunction | AsyncGeneratorFunction | Duplex | TransformStream}>` (or a tuple of those types)\1077Default: `pipe`10781046Like the [`stdin`](#optionsstdin), [`stdout`](#optionsstdout) and [`stderr`](#optionsstderr) options but for all file descriptors at once. For example, `{stdio: ['ignore', 'pipe', 'pipe']}` is the same as `{stdin: 'ignore', stdout: 'pipe', stderr: 'pipe'}`.1079Like the [`stdin`](#optionsstdin), [`stdout`](#optionsstdout) and [`stderr`](#optionsstderr) options but for all [file descriptors](https://en.wikipedia.org/wiki/File_descriptor) at once. For example, `{stdio: ['ignore', 'pipe', 'pipe']}` is the same as `{stdin: 'ignore', stdout: 'pipe', stderr: 'pipe'}`.10801048A single string can be used as a shortcut. For example, `{stdio: 'pipe'}` is the same as `{stdin: 'pipe', stdout: 'pipe', stderr: 'pipe'}`.1081A single string can be used [as a shortcut](docs/output.md#shortcut).10821050The array can have more than 3 items, to create additional file descriptors beyond `stdin`/`stdout`/`stderr`. For example, `{stdio: ['pipe', 'pipe', 'pipe', 'pipe']}` sets a fourth file descriptor.1083The array can have more than 3 items, to create [additional file descriptors](docs/output.md#additional-file-descriptors) beyond [`stdin`](#optionsstdin)/[`stdout`](#optionsstdout)/[`stderr`](#optionsstderr).10841052[More info.](https://nodejs.org/api/child_process.html#child_process_options_stdio)1085More info on [available values](docs/output.md), [streaming](docs/streams.md) and [transforms](docs/transform.md).10861087#### options.all10881089Type: `boolean`\1090Default: `false`10911059Add a [`subprocess.all`](#subprocessall) stream and a [`result.all`](#resultall) property. They contain the combined/[interleaved](#ensuring-all-output-is-interleaved) output of the subprocess' `stdout` and `stderr`.1092Add a [`subprocess.all`](#subprocessall) stream and a [`result.all`](#resultall) property.10931094[More info.](docs/output.md#interleaved-output)10951096#### options.lines10971098Type: `boolean`\1099Default: `false`11001101Set [`result.stdout`](#resultstdout), [`result.stderr`](#resultstdout), [`result.all`](#resultall) and [`result.stdio`](#resultstdio) as arrays of strings, splitting the subprocess' output into lines.11021068This cannot be used if the [`encoding`](#optionsencoding) option is binary.1103This cannot be used if the [`encoding`](#optionsencoding) option is [binary](docs/binary.md#binary-output).11041070By default, this applies to both `stdout` and `stderr`, but [different values can also be passed](#options).1105By default, this applies to both `stdout` and `stderr`, but [different values can also be passed](docs/output.md#stdoutstderr-specific-options).11061107[More info.](docs/lines.md#simple-splitting)11081109#### options.encoding11101074Type: `string`\1111Type: `'utf8' | 'utf16le' | 'buffer' | 'hex' | 'base64' | 'base64url' | 'latin1' | 'ascii'`\1112Default: `'utf8'`11131077If the subprocess outputs text, specifies its character encoding, either `'utf8'` or `'utf16le'`.1114If the subprocess outputs text, specifies its character encoding, either [`'utf8'`](https://en.wikipedia.org/wiki/UTF-8) or [`'utf16le'`](https://en.wikipedia.org/wiki/UTF-16).11151116If it outputs binary data instead, this should be either:1080- `'buffer'`: returns the binary output as an `Uint8Array`.1081- `'hex'`, `'base64'`, `'base64url'`, [`'latin1'`](https://nodejs.org/api/buffer.html#buffers-and-character-encodings) or [`'ascii'`](https://nodejs.org/api/buffer.html#buffers-and-character-encodings): encodes the binary output as a string.1117- `'buffer'`: returns the binary output as an [`Uint8Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array).1118- [`'hex'`](https://en.wikipedia.org/wiki/Hexadecimal), [`'base64'`](https://en.wikipedia.org/wiki/Base64), [`'base64url'`](https://en.wikipedia.org/wiki/Base64#URL_applications), [`'latin1'`](https://nodejs.org/api/buffer.html#buffers-and-character-encodings) or [`'ascii'`](https://nodejs.org/api/buffer.html#buffers-and-character-encodings): encodes the binary output as a string.11191120The output is available with [`result.stdout`](#resultstdout), [`result.stderr`](#resultstderr) and [`result.stdio`](#resultstdio).11211122[More info.](docs/binary.md)11231124#### options.stripFinalNewline11251126Type: `boolean`\1127Default: `true`
1 unmodified line
1129Strip the final [newline character](https://en.wikipedia.org/wiki/Newline) from the output.11301131If the [`lines`](#optionslines) option is true, this applies to each output line instead.11321094By default, this applies to both `stdout` and `stderr`, but [different values can also be passed](#options).1133By default, this applies to both `stdout` and `stderr`, but [different values can also be passed](docs/output.md#stdoutstderr-specific-options).11341135[More info.](docs/lines.md#newlines)11361137#### options.maxBuffer11381139Type: `number`\1140Default: `100_000_000`11411142Largest amount of data allowed on [`stdout`](#resultstdout), [`stderr`](#resultstderr) and [`stdio`](#resultstdio).11431103When this threshold is hit, the subprocess fails and [`error.isMaxBuffer`](#resultismaxbuffer) becomes `true`.1144By default, this applies to both `stdout` and `stderr`, but [different values can also be passed](docs/output.md#stdoutstderr-specific-options).11451105This is measured:1106- By default: in [characters](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/length).1107- If the [`encoding`](#optionsencoding) option is `'buffer'`: in bytes.1108- If the [`lines`](#optionslines) option is `true`: in lines.1109- If a [transform in object mode](docs/transform.md#object-mode) is used: in objects.1146[More info.](docs/output.md#big-output)11471111By default, this applies to both `stdout` and `stderr`, but [different values can also be passed](#options).11121148#### options.ipc11491150Type: `boolean`\1151Default: `true` if the [`node`](#optionsnode) option is enabled, `false` otherwise11521153Enables exchanging messages with the subprocess using [`subprocess.send(message)`](#subprocesssendmessage) and [`subprocess.on('message', (message) => {})`](#subprocessonmessage-message--void).11541155[More info.](docs/ipc.md)11561157#### options.serialization11581122Type: `string`\1159Type: `'json' | 'advanced'`\1160Default: `'advanced'`11611125Specify the kind of serialization used for sending messages between subprocesses when using the [`ipc`](#optionsipc) option:1126- `json`: Uses `JSON.stringify()` and `JSON.parse()`.1127- `advanced`: Uses [`v8.serialize()`](https://nodejs.org/api/v8.html#v8_v8_serialize_value)1162Specify the kind of serialization used for sending messages between subprocesses when using the [`ipc`](#optionsipc) option.11631129[More info.](https://nodejs.org/api/child_process.html#child_process_advanced_serialization)1164[More info.](docs/ipc.md#message-type)11651166#### options.detached11671168Type: `boolean`\1169Default: `false`11701136Prepare subprocess to run independently of the current process. Specific behavior depends on the platform.1171Run the subprocess independently from the current process.11721138[More info.](https://nodejs.org/api/child_process.html#child_process_options_detached).1173[More info.](docs/environment.md#background-subprocess)11741175#### options.cleanup11761177Type: `boolean`\1178Default: `true`11791145Kill the subprocess when the current process exits unless either:1146- the subprocess is [`detached`](#optionsdetached).1147- the current process is terminated abruptly, for example, with `SIGKILL` as opposed to `SIGTERM` or a normal exit.1180Kill the subprocess when the current process exits.11811182[More info.](docs/termination.md#current-process-exit)11831184#### options.timeout11851186Type: `number`\1187Default: `0`11881189If `timeout` is greater than `0`, the subprocess will be [terminated](#optionskillsignal) if it runs for longer than that amount of milliseconds.11901191On timeout, [`result.timedOut`](#resulttimedout) becomes `true`.11921193[More info.](docs/termination.md#timeout)11941195#### options.cancelSignal11961197Type: [`AbortSignal`](https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal)11981199You can abort the subprocess using [`AbortController`](https://developer.mozilla.org/en-US/docs/Web/API/AbortController).12001201When `AbortController.abort()` is called, [`result.isCanceled`](#resultiscanceled) becomes `true`.12021203[More info.](docs/termination.md#canceling)12041205#### options.forceKillAfterDelay12061207Type: `number | false`\1208Default: `5000`12091210If the subprocess is terminated but does not exit, forcefully exit it by sending [`SIGKILL`](https://en.wikipedia.org/wiki/Signal_(IPC)#SIGKILL).12111171The grace period is 5 seconds by default. This feature can be disabled with `false`.1212[More info.](docs/termination.md#forceful-termination)12131173This works when the subprocess is terminated by either:1174- the [`cancelSignal`](#optionscancelsignal), [`timeout`](#optionstimeout), [`maxBuffer`](#optionsmaxbuffer) or [`cleanup`](#optionscleanup) option1175- calling [`subprocess.kill()`](#subprocesskillsignal-error) with no arguments11761177This does not work when the subprocess is terminated by either:1178- calling [`subprocess.kill()`](#subprocesskillsignal-error) with an argument1179- calling [`process.kill(subprocess.pid)`](https://nodejs.org/api/process.html#processkillpid-signal)1180- sending a termination signal from another process11811182Also, 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.11831214#### options.killSignal12151216Type: `string | number`\1187Default: `SIGTERM`1217Default: `'SIGTERM'`12181189Signal used to terminate the subprocess when:1190- using the [`cancelSignal`](#optionscancelsignal), [`timeout`](#optionstimeout), [`maxBuffer`](#optionsmaxbuffer) or [`cleanup`](#optionscleanup) option1191- calling [`subprocess.kill()`](#subprocesskillsignal-error) with no arguments1219Default [signal](https://en.wikipedia.org/wiki/Signal_(IPC)) used to terminate the subprocess.12201193This can be either a name (like `"SIGTERM"`) or a number (like `9`).1221This can be either a name (like [`'SIGTERM'`](docs/termination.md#sigterm)) or a number (like `9`).12221223[More info.](docs/termination.md#default-signal)12241225#### options.argv012261197Type: `string`1227Type: `string`\1228Default: file being executed12291199Explicitly set the value of `argv[0]` sent to the subprocess. This will be set to `file` if not specified.1230Value of [`argv[0]`](https://nodejs.org/api/process.html#processargv0) sent to the subprocess.12311232#### options.uid12331203Type: `number`1234Type: `number`\1235Default: current user identifier12361205Sets the user identity of the subprocess.1237Sets the [user identifier](https://en.wikipedia.org/wiki/User_identifier) of the subprocess.12381239[More info.](docs/windows.md#uid-and-gid)12401241#### options.gid12421209Type: `number`1243Type: `number`\1244Default: current group identifier12451211Sets the group identity of the subprocess.1246Sets the [group identifier](https://en.wikipedia.org/wiki/Group_identifier) of the subprocess.12471248[More info.](docs/windows.md#uid-and-gid)12491250#### options.windowsVerbatimArguments12511252Type: `boolean`\1216Default: `false`1253Default: `true` if the [`shell`](#optionsshell) option is `true`, `false` otherwise12541218If `true`, no quoting or escaping of arguments is done on Windows. Ignored on other platforms. This is set to `true` automatically when the `shell` option is `true`.1255If `false`, escapes the command arguments on Windows.12561257[More info.](docs/windows.md#cmdexe-escaping)12581259#### options.windowsHide12601261Type: `boolean`\1262Default: `true`12631225On Windows, do not create a new console window. Please note this also prevents `CTRL-C` [from working](https://github.com/nodejs/node/issues/29837) on Windows.1264On Windows, do not create a new console window.12651227## Tips1266[More info.](docs/windows.md#console-window)12671229### Redirect stdin/stdout/stderr to multiple destinations1268### Transform options12691231The [`stdin`](#optionsstdin), [`stdout`](#optionsstdout) and [`stderr`](#optionsstderr) options can be an array of values.1232The following example redirects `stdout` to both the terminal and an `output.txt` file, while also retrieving its value programmatically.1270A transform or an [array of transforms](docs/transform.md#combining) can be passed to the [`stdin`](#optionsstdin), [`stdout`](#optionsstdout), [`stderr`](#optionsstderr) or [`stdio`](#optionsstdio) option.12711234```js1235const {stdout} = await execa('npm', ['install'], {stdout: ['inherit', './output.txt', 'pipe']});1236console.log(stdout);1237```1272A transform is either a [generator function](#transformoptionstransform) or a plain object with the following members.12731239When combining `inherit` with other values, please note that the subprocess will not be an interactive TTY, even if the current process is one.1274[More info.](docs/transform.md)12751241### Redirect a Node.js stream from/to stdin/stdout/stderr1276#### transformOptions.transform12771243When passing a Node.js stream to the [`stdin`](#optionsstdin), [`stdout`](#optionsstdout) or [`stderr`](#optionsstderr) 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.1278Type: `GeneratorFunction<string | Uint8Array | unknown>` | `AsyncGeneratorFunction<string | Uint8Array | unknown>`12791245```1246TypeError [ERR_INVALID_ARG_VALUE]: The argument 'stdio' is invalid.1247```1280Map or [filter](docs/transform.md#filtering) the [input](docs/input.md) or [output](docs/output.md) of the subprocess.12811249This limitation can be worked around by passing either:1250- a web stream ([`ReadableStream`](https://developer.mozilla.org/en-US/docs/Web/API/ReadableStream) or [`WritableStream`](https://developer.mozilla.org/en-US/docs/Web/API/WritableStream))1251- `[nodeStream, 'pipe']` instead of `nodeStream`1282More info [here](docs/transform.md#summary) and [there](docs/transform.md#sharing-state).12831253```diff1254- await execa(..., {stdout: nodeStream});1255+ await execa(..., {stdout: [nodeStream, 'pipe']});1256```1284#### transformOptions.final12851258### Retry on error1286Type: `GeneratorFunction<string | Uint8Array | unknown>` | `AsyncGeneratorFunction<string | Uint8Array | unknown>`12871260Safely handle failures by using automatic retries and exponential backoff with the [`p-retry`](https://github.com/sindresorhus/p-retry) package:1288Create additional lines after the last one.12891262```js1263import pRetry from 'p-retry';1290[More info.](docs/transform.md#finalizing)12911265const run = async () => {1266 const results = await execa('curl', ['-sSL', 'https://sindresorhus.com/unicorn']);1267 return results;1268};1292#### transformOptions.binary12931270console.log(await pRetry(run, {retries: 5}));1271```1294Type: `boolean`\1295Default: `false`12961273### Cancelling a subprocess1297If `true`, iterate over arbitrary chunks of `Uint8Array`s instead of line `string`s.12981275```js1276import {execa} from 'execa';1299[More info.](docs/binary.md#transforms)13001278const abortController = new AbortController();1279const subprocess = execa('node', [], {cancelSignal: abortController.signal});1301#### transformOptions.preserveNewlines13021281setTimeout(() => {1282 abortController.abort();1283}, 1000);1303Type: `boolean`\1304Default: `false`13051285try {1286 await subprocess;1287} catch (error) {1288 console.log(error.isTerminated); // true1289 console.log(error.isCanceled); // true1290}1291```1306If `true`, keep newlines in each `line` argument. Also, this allows multiple `yield`s to produces a single line.13071293### Execute the current package's binary1308[More info.](docs/lines.md#transforms)13091295Execa can be combined with [`get-bin-path`](https://github.com/ehmicky/get-bin-path) to test the current package's binary. As opposed to hard-coding the path to the binary, this validates that the `package.json` `bin` field is correctly set up.1310#### transformOptions.objectMode13111297```js1298import {getBinPath} from 'get-bin-path';1312Type: `boolean`\1313Default: `false`13141300const binPath = await getBinPath();1301await execa(binPath);1302```1315If `true`, allow [`transformOptions.transform`](#transformoptionstransform) and [`transformOptions.final`](#transformoptionsfinal) to return any type, not just `string` or `Uint8Array`.13161304### Ensuring `all` output is interleaved1317[More info.](docs/transform.md#object-mode)13181306The `subprocess.all` [stream](#subprocessall) and `result.all` [string/`Uint8Array`](#resultall) property are guaranteed to interleave [`stdout`](#resultstdout) and [`stderr`](#resultstderr).13071308However, for performance reasons, the subprocess might buffer and merge multiple simultaneous writes to `stdout` or `stderr`. This prevents proper interleaving.13091310For example, this prints `1 3 2` instead of `1 2 3` because both `console.log()` are merged into a single write.13111312```js1313import {execa} from 'execa';13141315const {all} = await execa('node', ['example.js'], {all: true});1316console.log(all);1317```13181319```js1320// example.js1321console.log('1'); // writes to stdout1322console.error('2'); // writes to stderr1323console.log('3'); // writes to stdout1324```13251326This can be worked around by using `setTimeout()`.13271328```js1329import {setTimeout} from 'timers/promises';13301331console.log('1');1332console.error('2');1333await setTimeout(0);1334console.log('3');1335```13361319## Related13201321- [gulp-execa](https://github.com/ehmicky/gulp-execa) - Gulp plugin for Execa1322- [nvexeca](https://github.com/ehmicky/nvexeca) - Run Execa using any Node.js version
5 unmodified lines