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
Provenance
- Commit
be91ecf- Tree
d3f6e82- Author
ehmicky <ehmicky@users.noreply.github.com>- Committer
GitHub <noreply@github.com>- Parent
fdd8a9f
32 files changed+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>6+7+# 🔍 Differences with Bash and zx8+9+This 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.16+17+## Flexibility18+19+Unlike 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).20+21+## Shell22+23+The 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.24+25+This is more cross-platform. For example, your code works the same on Windows machines without Bash installed.26+27+Also, there is no shell syntax to remember: everything is just plain JavaScript.28+29+If you really need a shell though, the [`shell`](shell.md) option can be used.30+31+## Simplicity32+33+Execa's scripting API mostly consists of only two methods: [`` $`command` ``](shell.md) and [`$(options)`](execution.md#globalshared-options).34+35+[No special binary](#main-binary) is recommended, no [global variable](#global-variables) is injected: scripts are regular Node.js files.36+37+Execa 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.38+39+## Modularity40+41+zx includes many builtin utilities: `fetch()`, `question()`, `sleep()`, `stdin()`, `retry()`, `spinner()`, `chalk`, `fs-extra`, `os`, `path`, `globby`, `yaml`, `minimist`, `which`, Markdown scripts, remote scripts.42+43+Execa 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.44+45+## Performance46+47+Spawning a shell for every command comes at a performance cost, which Execa avoids.48+49+Also, [local binaries](#local-binaries) can be directly executed without using `npx`.50+51+## Debugging52+53+Subprocesses can be hard to debug, which is why Execa includes a [`verbose`](#verbose-mode) option.54+55+Also, 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).56+57+Finally, unlike Bash and zx, which are stateful (options, current directory, etc.), Execa is [purely functional](#current-directory), which also helps with debugging.58+59+## Examples60+61+### Main binary62+63+```sh64+# Bash65+bash file.sh66+```67+68+```js69+// zx70+zx file.js71+72+// or a shebang can be used:73+// #!/usr/bin/env zx74+```75+76+```js77+// Execa scripts are just regular Node.js files78+node file.js79+```80+81+### Global variables82+83+```js84+// zx85+await $`echo example`;86+```87+88+```js89+// Execa90+import {$} from 'execa';91+92+await $`echo example`;93+```94+95+[More info.](execution.md)96+97+### Command execution98+99+```sh100+# Bash101+echo example102+```103+104+```js105+// zx106+await $`echo example`;107+```108+109+```js110+// Execa111+await $`echo example`;112+```113+114+### Multiline commands115+116+```sh117+# Bash118+npm run build \119+ --example-flag-one \120+ --example-flag-two121+```122+123+```js124+// zx125+await $`npm run build ${[126+ '--example-flag-one',127+ '--example-flag-two',128+]}`;129+```130+131+```js132+// Execa133+await $`npm run build134+ --example-flag-one135+ --example-flag-two`;136+```137+138+[More info.](execution.md#multiple-lines)139+140+### Concatenation141+142+```sh143+# Bash144+tmpDirectory="/tmp"145+mkdir "$tmpDirectory/filename"146+```147+148+```js149+// zx150+const tmpDirectory = '/tmp'151+await $`mkdir ${tmpDirectory}/filename`;152+```153+154+```js155+// Execa156+const tmpDirectory = '/tmp'157+await $`mkdir ${tmpDirectory}/filename`;158+```159+160+[More info.](execution.md#concatenation)161+162+### Variable substitution163+164+```sh165+# Bash166+echo $LANG167+```168+169+```js170+// zx171+await $`echo $LANG`;172+```173+174+```js175+// Execa176+await $`echo ${process.env.LANG}`;177+```178+179+[More info.](input.md#environment-variables)180+181+### Escaping182+183+```sh184+# Bash185+echo 'one two'186+```187+188+```js189+// zx190+await $`echo ${'one two'}`;191+```192+193+```js194+// Execa195+await $`echo ${'one two'}`;196+```197+198+[More info.](escaping.md)199+200+### Escaping multiple arguments201+202+```sh203+# Bash204+echo 'one two' '$'205+```206+207+```js208+// zx209+await $`echo ${['one two', '$']}`;210+```211+212+```js213+// Execa214+await $`echo ${['one two', '$']}`;215+```216+217+[More info.](execution.md#multiple-arguments)218+219+### Subcommands220+221+```sh222+# Bash223+echo "$(echo example)"224+```225+226+```js227+// zx228+const example = await $`echo example`;229+await $`echo ${example}`;230+```231+232+```js233+// Execa234+const example = await $`echo example`;235+await $`echo ${example}`;236+```237+238+[More info.](execution.md#subcommands)239+240+### Serial commands241+242+```sh243+# Bash244+echo one && echo two245+```246+247+```js248+// zx249+await $`echo one && echo two`;250+```251+252+```js253+// Execa254+await $`echo one`;255+await $`echo two`;256+```257+258+### Parallel commands259+260+```sh261+# Bash262+echo one &263+echo two &264+```265+266+```js267+// zx268+await Promise.all([$`echo one`, $`echo two`]);269+```270+271+```js272+// Execa273+await Promise.all([$`echo one`, $`echo two`]);274+```275+276+### Global/shared options277+278+```sh279+# Bash280+options="timeout 5"281+$options echo one282+$options echo two283+$options echo three284+```285+286+```js287+// zx288+const timeout = '5s';289+await $`echo one`.timeout(timeout);290+await $`echo two`.timeout(timeout);291+await $`echo three`.timeout(timeout);292+```293+294+```js295+// Execa296+import {$ as $_} from 'execa';297+298+const $ = $_({timeout: 5000});299+300+await $`echo one`;301+await $`echo two`;302+await $`echo three`;303+```304+305+[More info.](execution.md#globalshared-options)306+307+### Environment variables308+309+```sh310+# Bash311+EXAMPLE=1 example_command312+```313+314+```js315+// zx316+$.env.EXAMPLE = '1';317+await $`example_command`;318+delete $.env.EXAMPLE;319+```320+321+```js322+// Execa323+await $({env: {EXAMPLE: '1'}})`example_command`;324+```325+326+[More info.](input.md#environment-variables)327+328+### Local binaries329+330+```sh331+# Bash332+npx tsc --version333+```334+335+```js336+// zx337+await $`npx tsc --version`;338+```339+340+```js341+// Execa342+await $`tsc --version`;343+```344+345+[More info.](environment.md#local-binaries)346+347+### Builtin utilities348+349+```js350+// zx351+const content = await stdin();352+```353+354+```js355+// Execa356+import getStdin from 'get-stdin';357+358+const content = await getStdin();359+```360+361+### Printing to stdout362+363+```sh364+# Bash365+echo example366+```367+368+```js369+// zx370+echo`example`;371+```372+373+```js374+// Execa375+console.log('example');376+```377+378+### Silent stderr379+380+```sh381+# Bash382+echo example 2> /dev/null383+```384+385+```js386+// zx387+await $`echo example`.stdio('inherit', 'pipe', 'ignore');388+```389+390+```js391+// Execa does not print stdout/stderr by default392+await $`echo example`;393+```394+395+### Verbose mode396+397+```sh398+# Bash399+set -v400+echo example401+```402+403+```js404+// zx >=8405+await $`echo example`.verbose();406+407+// or:408+$.verbose = true;409+```410+411+```js412+// Execa413+await $({verbose: 'full'})`echo example`;414+```415+416+Or:417+418+```419+NODE_DEBUG=execa node file.js420+```421+422+Which prints:423+424+```425+[19:49:00.360] [0] $ echo example426+example427+[19:49:00.383] [0] √ (done in 23ms)428+```429+430+[More info.](debugging.md#verbose-mode)431+432+### Piping stdout to another command433+434+```sh435+# Bash436+echo npm run build | sort | head -n2437+```438+439+```js440+// zx441+await $`npm run build | sort | head -n2`;442+```443+444+```js445+// Execa446+await $`npm run build`447+ .pipe`sort`448+ .pipe`head -n2`;449+```450+451+[More info.](pipe.md)452+453+### Piping stdout and stderr to another command454+455+```sh456+# Bash457+echo example |& cat458+```459+460+```js461+// zx462+const echo = $`echo example`;463+const cat = $`cat`;464+echo.pipe(cat)465+echo.stderr.pipe(cat.stdin);466+await Promise.all([echo, cat]);467+```468+469+```js470+// Execa471+await $({all: true})`echo example`472+ .pipe({from: 'all'})`cat`;473+```474+475+[More info.](pipe.md#source-file-descriptor)476+477+### Piping stdout to a file478+479+```sh480+# Bash481+echo example > output.txt482+```483+484+```js485+// zx486+await $`echo example`.pipe(fs.createWriteStream('output.txt'));487+```488+489+```js490+// Execa491+await $({stdout: {file: 'output.txt'}})`echo example`;492+```493+494+[More info.](output.md#file-output)495+496+### Piping stdin from a file497+498+```sh499+# Bash500+echo example < input.txt501+```502+503+```js504+// zx505+const cat = $`cat`;506+fs.createReadStream('input.txt').pipe(cat.stdin);507+await cat;508+```509+510+```js511+// Execa512+await $({inputFile: 'input.txt'})`cat`;513+```514+515+[More info.](input.md#file-input)516+517+### Iterate over output lines518+519+```sh520+# Bash521+while read522+do523+ if [[ "$REPLY" == *ERROR* ]]524+ then525+ echo "$REPLY"526+ fi527+done < <(npm run build)528+```529+530+```js531+// zx does not allow proper iteration.532+// For example, the iteration does not handle subprocess errors.533+```534+535+```js536+// Execa537+for await (const line of $`npm run build`) {538+ if (line.includes('ERROR')) {539+ console.log(line);540+ }541+}542+```543+544+[More info.](lines.md#progressive-splitting)545+546+### Errors547+548+```sh549+# Bash communicates errors only through the exit code and stderr550+timeout 1 sleep 2551+echo $?552+```553+554+```js555+// zx556+const {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+```583+584+```js585+// Execa586+const {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+```625+626+[More info.](errors.md)627+628+### Exit codes629+630+```sh631+# Bash632+false633+echo $?634+```635+636+```js637+// zx638+const {exitCode} = await $`false`.nothrow();639+echo`${exitCode}`;640+```641+642+```js643+// Execa644+const {exitCode} = await $({reject: false})`false`;645+console.log(exitCode);646+```647+648+[More info.](errors.md#exit-code)649+650+### Timeouts651+652+```sh653+# Bash654+timeout 5 echo example655+```656+657+```js658+// zx659+await $`echo example`.timeout('5s');660+```661+662+```js663+// Execa664+await $({timeout: 5000})`echo example`;665+```666+667+[More info.](termination.md#timeout)668+669+### Current filename670+671+```sh672+# Bash673+echo "$(basename "$0")"674+```675+676+```js677+// zx678+await $`echo ${__filename}`;679+```680+681+```js682+// Execa683+await $`echo ${import.meta.filename}`;684+```685+686+### Current directory687+688+```sh689+# Bash690+cd project691+```692+693+```js694+// zx695+cd('project');696+697+// or:698+$.cwd = 'project';699+```700+701+```js702+// Execa703+const $$ = $({cwd: 'project'});704+```705+706+[More info.](environment.md#current-directory)707+708+### Multiple current directories709+710+```sh711+# Bash712+pushd project713+pwd714+popd715+pwd716+```717+718+```js719+// zx720+within(async () => {721+ cd('project');722+ await $`pwd`;723+});724+725+await $`pwd`;726+```727+728+```js729+// Execa730+await $({cwd: 'project'})`pwd`;731+await $`pwd`;732+```733+734+[More info.](environment.md#current-directory)735+736+### Background subprocess737+738+```sh739+# Bash740+echo one &741+```742+743+```js744+// zx does not allow setting the `detached` option745+```746+747+```js748+// Execa749+await $({detached: true})`echo one`;750+```751+752+[More info.](environment.md#background-subprocess)753+754+### IPC755+756+```sh757+# Bash does not allow simple IPC758+```759+760+```js761+// zx does not allow simple IPC762+```763+764+```js765+// Execa766+const subprocess = $({ipc: true})`node script.js`;767+768+subprocess.on('message', message => {769+ if (message === 'ping') {770+ subprocess.send('pong');771+ }772+});773+```774+775+[More info.](ipc.md)776+777+### Transforms778+779+```sh780+# Bash does not allow transforms781+```782+783+```js784+// zx does not allow transforms785+```786+787+```js788+// Execa789+const transform = function * (line) {790+ if (!line.includes('secret')) {791+ yield line;792+ }793+};794+795+await $({stdout: [transform, 'inherit']})`echo ${'This is a secret.'}`;796+```797+798+[More info.](transform.md)799+800+### Cancelation801+802+```sh803+# Bash804+kill $PID805+```806+807+```js808+// zx809+subprocess.kill();810+```811+812+```js813+// Execa814+// Can specify an error message and stack trace815+subprocess.kill(error);816+817+// Or use an `AbortSignal`818+const controller = new AbortController();819+await $({signal: controller.signal})`node long-script.js`;820+```821+822+[More info.](termination.md#canceling)823+824+### Interleaved output825+826+```sh827+# Bash prints stdout and stderr interleaved828+```829+830+```js831+// zx separates stdout and stderr832+const {stdout, stderr} = await $`node example.js`;833+```834+835+```js836+// Execa can interleave stdout and stderr837+const {all} = await $({all: true})`node example.js`;838+```839+840+[More info.](output.md#interleaved-output)841+842+### PID843+844+```sh845+# Bash846+echo example &847+echo $!848+```849+850+```js851+// zx does not return `subprocess.pid`852+```853+854+```js855+// Execa856+const {pid} = $`echo example`;857+```858+859+[More info.](termination.md#inter-process-termination)860+861+<hr>862+863+[**Previous**: 📎 Windows](windows.md)\864+[**Top**: Table of contents](../readme.md#documentation)added:docs/binary.md+79 added
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879<picture> <source media="(prefers-color-scheme: dark)" srcset="../media/logo_dark.svg"> <img alt="execa logo" src="../media/logo.svg" width="400"></picture><br>
# 🤖 Binary data
## Binary input
There are multiple ways to pass binary input using the [`stdin`](../readme.md#optionsstdin), [`input`](../readme.md#optionsinput) or [`inputFile`](../readme.md#optionsinputfile) options: `Uint8Array`s, [files](input.md#file-input), [streams](streams.md) or [other subprocesses](pipe.md).
This is required if the subprocess input includes [null bytes](https://en.wikipedia.org/wiki/Null_character).
```jsimport {execa} from 'execa';
const binaryData = new Uint8Array([/* ... */]);await execa({stdin: binaryData})`hexdump`;```
## Binary output
By default, the subprocess [output](../readme.md#resultstdout) is a [UTF8](https://en.wikipedia.org/wiki/UTF-8) string. If it is binary, the [`encoding`](../readme.md#optionsencoding) option should be set to `'buffer'` instead. The output will be an [`Uint8Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array).
```jsconst {stdout} = await execa({encoding: 'buffer'})`zip -r - input.txt`;console.log(stdout.byteLength);```
## Encoding
When the output is binary, the [`encoding`](../readme.md#optionsencoding) option can also be set to [`'hex'`](https://en.wikipedia.org/wiki/Hexadecimal), [`'base64'`](https://en.wikipedia.org/wiki/Base64) or [`'base64url'`](https://en.wikipedia.org/wiki/Base64#URL_applications). The output will be a string then.
```jsconst {stdout} = await execa({encoding: 'hex'})`zip -r - input.txt`;console.log(stdout); // Hexadecimal string```
## Iterable
By default, the subprocess [iterates](lines.md#progressive-splitting) over line strings. However, if the [`encoding`](../readme.md#optionsencoding) subprocess option is binary, or if the [`binary`](../readme.md#readableoptionsbinary) iterable option is `true`, it iterates over arbitrary chunks of [`Uint8Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array) data instead.
```jsfor await (const data of execa({encoding: 'buffer'})`zip -r - input.txt`) { /* ... */}```
## Transforms
The same applies to transforms. When the [`encoding`](../readme.md#optionsencoding) subprocess option is binary, or when the [`binary`](../readme.md#transformoptionsbinary) transform option is `true`, it iterates over arbitrary chunks of [`Uint8Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array) data instead.
However, transforms can always `yield` either a `string` or an `Uint8Array`, regardless of whether the output is binary or not.
```jsconst transform = function * (data) { /* ... */}
await execa({stdout: {transform, binary: true}})`zip -r - input.txt`;```
## Streams
[Streams produced](streams.md#converting-a-subprocess-to-a-stream) by [`subprocess.readable()`](../readme.md#subprocessreadablereadableoptions) and [`subprocess.duplex()`](../readme.md#subprocessduplexduplexoptions) are binary by default, which means they iterate over arbitrary [`Buffer`](https://nodejs.org/api/buffer.html#class-buffer) chunks. However, if the [`binary`](../readme.md#readableoptionsbinary) option is `false`, they iterate over line strings instead, and the stream is [in object mode](https://nodejs.org/api/stream.html#object-mode).
```jsconst readable = execa`npm run build`.readable({binary: false});readable.on('data', lineString => { /* ... */});```
<hr>
[**Next**: 🧙 Transforms](transform.md)\[**Previous**: 📃 Text lines](lines.md)\[**Top**: Table of contents](../readme.md#documentation)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>6+7+# 🐛 Debugging8+9+## Command10+11+[`error.command`](../readme.md#resultcommand) contains the file and [arguments](input.md#command-arguments) that were run. It is intended for logging or debugging.12+13+[`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.14+15+Since 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).16+17+```js18+import {execa} from 'execa';19+20+try {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+```28+29+## Duration30+31+```js32+try {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+```40+41+## Verbose mode42+43+### Short mode44+45+When 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)).46+47+```js48+// build.js49+await execa({verbose: 'short'})`npm run build`;50+```51+52+```sh53+$ node build.js54+[20:36:11.043] [0] $ npm run build55+[20:36:11.885] [0] ✔ (done in 842ms)56+```57+58+### Full mode59+60+When 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)).61+62+The 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).66+67+```js68+// build.js69+await execa({verbose: 'full'})`npm run build`;70+```71+72+```sh73+$ node build.js74+[20:36:11.043] [0] $ npm run build75+Building application...76+Done building.77+[20:36:11.885] [0] ✔ (done in 842ms)78+```79+80+### Global mode81+82+When 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.83+84+```js85+// build.js86+87+// This is logged by default88+await execa`npm run build`;89+// This is not logged90+await execa({verbose: 'none'})`npm run test`;91+```92+93+```sh94+$ NODE_DEBUG=execa node build.js95+[20:36:11.043] [0] $ npm run build96+Building application...97+Done building.98+[20:36:11.885] [0] ✔ (done in 842ms)99+```100+101+<hr>102+103+[**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
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475<picture> <source media="(prefers-color-scheme: dark)" srcset="../media/logo_dark.svg"> <img alt="execa logo" src="../media/logo.svg" width="400"></picture><br>
# 🌐 Environment
## Current directory
The [current directory](https://en.wikipedia.org/wiki/Working_directory) when running the command can be set with the [`cwd`](../readme.md#optionscwd) option.
```jsimport {execa} from 'execa';
await execa({cwd: '/path/to/cwd'})`npm run build`;```
And be retrieved with the [`result.cwd`](../readme.md#resultcwd) property.
```jsconst {cwd} = await execa`npm run build`;```
## Local binaries
Package managers like `npm` install local binaries in `./node_modules/.bin`.
```js$ npm install -D eslint```
```jsawait execa('./node_modules/.bin/eslint');```
The [`preferLocal`](../readme.md#optionspreferlocal) option can be used to execute those local binaries.
```jsawait execa('eslint', {preferLocal: true});```
Those are searched in the current or any parent directory. The [`localDir`](../readme.md#optionslocaldir) option can select a different directory.
```jsawait execa('eslint', {preferLocal: true, localDir: '/path/to/dir'});```
## Current package's binary
Execa 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`](https://docs.npmjs.com/cli/v10/configuring-npm/package-json#bin) field is correctly set up.
```jsimport {execa} from 'execa';import {getBinPath} from 'get-bin-path';
const binPath = await getBinPath();await execa(binPath);```
## Background subprocess
When the [`detached`](../readme.md#optionsdetached) option is `true`, the subprocess [runs independently](https://en.wikipedia.org/wiki/Background_process) from the current process.
Specific behavior depends on the platform. [More info.](https://nodejs.org/api/child_process.html#child_process_options_detached)
```jsawait execa({detached: true})`npm run start`;```
<hr>
[**Next**: ❌ Errors](errors.md)\[**Previous**: 🐢 Node.js files](node.md)\[**Top**: Table of contents](../readme.md#documentation)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>6+7+# ❌ Errors8+9+## Subprocess failure10+11+When 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`.12+13+```js14+import {execa, ExecaError} from 'execa';15+16+try {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+```25+26+## Preventing exceptions27+28+When the [`reject`](../readme.md#optionsreject) option is `false`, the `error` is returned instead.29+30+```js31+const resultOrError = await execa`npm run build`;32+if (resultOrError.failed) {33+ console.error(resultOrError);34+}35+```36+37+## Exit code38+39+The 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).40+41+```js42+try {43+ await execa`npm run build`;44+} catch (error) {45+ // Either non-0 integer or undefined46+ console.error(error.exitCode);47+}48+```49+50+## Failure reason51+52+The 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.57+58+Otherwise, 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.63+64+```js65+try {66+ await execa`npm run build`;67+} catch (error) {68+ if (error.timedOut) {69+ handleTimeout(error);70+ }71+72+ throw error;73+}74+```75+76+## Error message77+78+For 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).81+82+[`error.shortMessage`](../readme.md#errorshortmessage) is the same but without `stdout`/`stderr`.83+84+[`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).85+86+```js87+try {88+ await execa`npm run build`;89+} catch (error) {90+ console.error(error.originalMessage);91+ // The task "build" does not exist.92+93+ console.error(error.shortMessage);94+ // Command failed with exit code 3: npm run build95+ // The task "build" does not exist.96+97+ 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+```104+105+## Retry on error106+107+Safely handle failures by using automatic retries and exponential backoff with the [`p-retry`](https://github.com/sindresorhus/p-retry) package.108+109+```js110+import pRetry from 'p-retry';111+import {execa} from 'execa';112+113+const run = () => execa`curl -sSL https://sindresorhus.com/unicorn`;114+console.log(await pRetry(run, {retries: 5}));115+```116+117+<hr>118+119+[**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>6+7+# 💬 Escaping/quoting8+9+## Array syntax10+11+When 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.12+13+```js14+import {execa} from 'execa';15+16+await execa('npm', ['run', 'task with space']);17+```18+19+## Template string syntax20+21+The same applies when using the [template string syntax](execution.md#template-string-syntax). However, spaces, tabs and newlines must use `${}`.22+23+```js24+await execa`npm run ${'task with space'}`;25+```26+27+## User-defined input28+29+The above syntaxes allow the file and its arguments to be user-defined by passing a variable.30+31+```js32+const command = 'npm';33+const commandArguments = ['run', 'task with space'];34+35+await execa(command, commandArguments);36+await execa`${command} ${commandArguments}`;37+```38+39+However, [`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 string42+43+This 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.44+45+```js46+for await (const commandAndArguments of getReplLine()) {47+ await execaCommand(commandAndArguments);48+}49+```50+51+Arguments 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.52+53+```js54+await execaCommand('npm run task\\ with\\ space');55+```56+57+## Shells58+59+[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.60+61+If 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.62+63+```js64+await execa({shell: true})`npm ${'run'} ${'task with space'}`;65+// Is the same as:66+await execa({shell: true})`npm run task with space`;67+```68+69+Therefore, you need to manually quote the arguments, using the shell-specific syntax.70+71+```js72+await execa({shell: true})`npm ${'run'} ${'"task with space"'}`;73+// Is the same as:74+await execa({shell: true})`npm run "task with space"`;75+```76+77+Sometimes 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.78+79+```js80+$`ssh host ${'npm run "task with space"'}`;81+```82+83+<hr>84+85+[**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>6+7+# ▶️ Basic execution8+9+## Array syntax10+11+```js12+import {execa} from 'execa';13+14+await execa('npm', ['run', 'build']);15+```16+17+## Template string syntax18+19+All [available methods](../readme.md#methods) can use either the [array syntax](#array-syntax) or the template string syntax, which are equivalent.20+21+```js22+await execa`npm run build`;23+```24+25+### String argument26+27+```js28+await execa`npm run ${'task with space'}`;29+```30+31+### Number argument32+33+```js34+await execa`npm run build --concurrency ${2}`;35+```36+37+### Subcommands38+39+```js40+const result = await execa`get-concurrency`;41+42+// Uses `result.stdout`43+await execa`npm run build --concurrency ${result}`;44+```45+46+### Concatenation47+48+```js49+const tmpDirectory = '/tmp';50+await execa`mkdir ${tmpDirectory}/filename`;51+```52+53+### Multiple arguments54+55+```js56+const result = await execa`get-concurrency`;57+58+await execa`npm ${['run', 'build', '--concurrency', 2]}`;59+```60+61+### Multiple lines62+63+```js64+await execa`npm run build65+ --concurrency 266+ --fail-fast`;67+```68+69+## Options70+71+[Options](../readme.md#options) can be passed to influence the execution's behavior.72+73+### Array syntax74+75+```js76+await execa('npm', ['run', 'build'], {timeout: 5000});77+```78+79+### Template string syntax80+81+```js82+await execa({timeout: 5000})`npm run build`;83+```84+85+### Global/shared options86+87+```js88+const timedExeca = execa({timeout: 5000});89+90+await timedExeca('npm', ['run', 'build']);91+await timedExeca`npm run test`;92+```93+94+## Return value95+96+### Subprocess97+98+The 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).99+100+```js101+const subprocess = execa`npm run build`;102+console.log(subprocess.pid);103+```104+105+### Result106+107+The subprocess is also a `Promise` that resolves with the [`result`](../readme.md#result).108+109+```js110+const {stdout} = await execa`npm run build`;111+```112+113+### Synchronous execution114+115+[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.116+117+```js118+import {execaSync} from 'execa';119+120+const {stdout} = execaSync`npm run build`;121+```122+123+Synchronous 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.133+134+<hr>135+136+[**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>6+7+# 🎹 Input8+9+## Command arguments10+11+The simplest way to pass input to a subprocess is to use command arguments.12+13+```js14+import {execa} from 'execa';15+16+const commandArgument = 'build';17+await execa`node child.js ${commandArgument}`;18+```19+20+If the subprocess is a Node.js file, those are available using [`process.argv`](https://nodejs.org/api/process.html#processargv).21+22+```js23+// child.js24+import process from 'node:process';25+26+const commandArgument = process.argv[2];27+```28+29+## Environment variables30+31+Unlike [command arguments](#command-arguments), [environment variables](https://en.wikipedia.org/wiki/Environment_variable) have names. They are commonly used to configure applications.32+33+If 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.34+35+```js36+// Keep the current process' environment variables, and set `NO_COLOR`37+await execa({env: {NO_COLOR: 'true'})`node child.js`;38+// Discard the current process' environment variables, only pass `NO_COLOR`39+await execa({env: {NO_COLOR: 'true'}, extendEnv: false)`node child.js`;40+```41+42+If the subprocess is a Node.js file, environment variables are available using [`process.env`](https://nodejs.org/api/process.html#processenv).43+44+```js45+// child.js46+import process from 'node:process';47+48+console.log(process.env.NO_COLOR);49+```50+51+## String input52+53+Alternatively, 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).54+55+If the input is already available as a string, it can be passed directly to the [`input`](../readme.md#optionsinput) option.56+57+```js58+await execa({input: 'stdinInput'})`npm run scaffold`;59+```60+61+The [`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).62+63+```js64+await execa({stdin: [['stdinInput']]})`npm run scaffold`;65+```66+67+## Ignore input68+69+```js70+const subprocess = execa({stdin: 'ignore'})`npm run scaffold`;71+console.log(subprocess.stdin); // undefined72+await subprocess;73+```74+75+## File input76+77+```js78+await execa({inputFile: './input.txt'})`npm run scaffold`;79+// Or:80+await execa({stdin: {file: './input.txt'}})`npm run scaffold`;81+// Or:82+await execa({stdin: new URL('file:///path/to/input.txt')})`npm run scaffold`;83+```84+85+## Terminal input86+87+The 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.88+89+```js90+await execa({stdin: 'inherit'})`npm run scaffold`;91+```92+93+## Additional file descriptors94+95+The [`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).96+97+```js98+// Pass input to the file descriptor number 399+await execa({100+ stdio: ['pipe', 'pipe', 'pipe', new Uint8Array([/* ... */])],101+})`npm run build`;102+```103+104+<hr>105+106+[**Next**: 📢 Output](output.md)\107+[**Previous**: 🏁 Termination](termination.md)\108+[**Top**: Table of contents](../readme.md#documentation)added:docs/ipc.md+54 added
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354<picture> <source media="(prefers-color-scheme: dark)" srcset="../media/logo_dark.svg"> <img alt="execa logo" src="../media/logo.svg" width="400"></picture><br>
# 📞 Inter-process communication
## Exchanging messages
When the [`ipc`](../readme.md#optionsipc) option is `true`, the current process and subprocess can exchange messages. This only works if the subprocess is a Node.js file.
The `ipc` option defaults to `true` when using [`execaNode()`](node.md#run-nodejs-files) or the [`node`](node.md#run-nodejs-files) option.
The current process sends messages with [`subprocess.send(message)`](../readme.md#subprocesssendmessage) and receives them with [`subprocess.on('message', (message) => {})`](../readme.md#subprocessonmessage-message--void). The subprocess sends messages with [`process.send(message)`](https://nodejs.org/api/process.html#processsendmessage-sendhandle-options-callback) and [`process.on('message', (message) => {})`](https://nodejs.org/api/process.html#event-message).
More info on [sending](https://nodejs.org/api/child_process.html#subprocesssendmessage-sendhandle-options-callback) and [receiving](https://nodejs.org/api/child_process.html#event-message) messages.
```js// parent.jsimport {execaNode} from 'execa';
const subprocess = execaNode`child.js`;subprocess.on('message', messageFromChild => { /* ... */});subprocess.send('Hello from parent');```
```js// child.jsimport process from 'node:process';
process.on('message', messageFromParent => { /* ... */});process.send('Hello from child');```
## Message type
By default, messages are serialized using [`structuredClone()`](https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Structured_clone_algorithm). This supports most types including objects, arrays, `Error`, `Date`, `RegExp`, `Map`, `Set`, `bigint`, `Uint8Array`, and circular references. This throws when passing functions, symbols or promises (including inside an object or array).
To limit messages to JSON instead, the [`serialization`](../readme.md#optionsserialization) option can be set to `'json'`.
```jsconst subprocess = execaNode({serialization: 'json'})`child.js`;```
<hr>
[**Next**: 🐛 Debugging](debugging.md)\[**Previous**: ⏳️ Streams](streams.md)\[**Top**: Table of contents](../readme.md#documentation)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>6+7+# 📃 Text lines8+9+## Simple splitting10+11+If the [`lines`](../readme.md#optionslines) option is `true`, the output is split into lines, as an array of strings.12+13+```js14+import {execa} from 'execa';15+16+const lines = await execa({lines: true})`npm run build`;17+console.log(lines.join('\n'));18+```19+20+## Iteration21+22+### Progressive splitting23+24+The subprocess' return value is an [async iterable](../readme.md#subprocesssymbolasynciterator). It iterates over the output's lines while the subprocess is still running.25+26+```js27+for await (const line of execa`npm run build`) {28+ if (line.includes('ERROR')) {29+ console.log(line);30+ }31+}32+```33+34+Alternatively, [`subprocess.iterable()`](../readme.md#subprocessiterablereadableoptions) can be called to pass [iterable options](../readme.md#readableoptions).35+36+The 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).37+38+```js39+for await (const line of execa`npm run build`.iterable())) {40+ /* ... */41+}42+```43+44+### Stdout/stderr45+46+By 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).47+48+```js49+for await (const stderrLine of execa`npm run build`.iterable({from: 'stderr'})) {50+ /* ... */51+}52+```53+54+## Newlines55+56+### Final newline57+58+The final newline is stripped from the output's last line, unless the [`stripFinalNewline`](../readme.md#optionsstripfinalnewline) option is `false`.59+60+```js61+const {stdout} = await execa({stripFinalNewline: false})`npm run build`;62+console.log(stdout.endsWith('\n')); // true63+```64+65+### Array of lines66+67+When using the [`lines`](#simple-splitting) option, newlines are stripped from each line, unless the [`stripFinalNewline`](../readme.md#optionsstripfinalnewline) option is `false`.68+69+```js70+// Each line now ends with '\n'.71+// The last `line` might or might not end with '\n', depending on the output.72+const lines = await execa({lines: true, stripFinalNewline: false})`npm run build`;73+console.log(lines.join(''));74+```75+76+### Iterable77+78+When [iterating](#progressive-splitting) over lines, newlines are stripped from each line, unless the [`preserveNewlines`](../readme.md#readableoptionspreservenewlines) iterable option is `true`.79+80+This 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`.81+82+```js83+// `line` now ends with '\n'.84+// The last `line` might or might not end with '\n', depending on the output.85+for await (const line of execa`npm run build`.iterable({preserveNewlines: true})) {86+ /* ... */87+}88+```89+90+### Transforms91+92+When using [transforms](transform.md), newlines are stripped from each `line` argument, unless the [`preserveNewlines`](../readme.md#transformoptionspreservenewlines) transform option is `true`.93+94+```js95+// `line` now ends with '\n'.96+// The last `line` might or might not end with '\n', depending on the output.97+const transform = function * (line) { /* ... */ };98+99+await execa({stdout: {transform, preserveNewlines: true}})`npm run build`;100+```101+102+Each `yield` produces at least one line. Calling `yield` multiple times or calling `yield *` produces multiples lines.103+104+```js105+const transform = function * (line) {106+ yield 'Important note:';107+ yield 'Read the comments below.';108+109+ // Or:110+ yield * [111+ 'Important note:',112+ 'Read the comments below.',113+ ];114+115+ // Is the same as:116+ yield 'Important note:\nRead the comments below.\n';117+118+ yield line;119+};120+121+await execa({stdout: transform})`npm run build`;122+```123+124+However, if the [`preserveNewlines`](../readme.md#transformoptionspreservenewlines) transform option is `true`, multiple `yield`s produce a single line instead.125+126+```js127+const transform = function * (line) {128+ yield 'Important note: ';129+ yield 'Read the comments below.\n';130+131+ // Is the same as:132+ yield 'Important note: Read the comments below.\n';133+134+ yield line;135+};136+137+await execa({stdout: {transform, preserveNewlines: true}})`npm run build`;138+```139+140+<hr>141+142+[**Next**: 🤖 Binary data](binary.md)\143+[**Previous**: 📢 Output](output.md)\144+[**Top**: Table of contents](../readme.md#documentation)added:docs/node.md+43 added
12345678910111213141516171819202122232425262728293031323334353637383940414243<picture> <source media="(prefers-color-scheme: dark)" srcset="../media/logo_dark.svg"> <img alt="execa logo" src="../media/logo.svg" width="400"></picture><br>
# 🐢 Node.js files
## Run Node.js files
```jsimport {execaNode, execa} from 'execa';
await execaNode('file.js');// Is the same as:await execa('file.js', {node: true});// Or:await execa('node', ['file.js']);```
## Node.js [CLI flags](https://nodejs.org/api/cli.html#options)
```jsawait execaNode('file.js', {nodeOptions: ['--no-warnings']});```
## Node.js version
[`get-node`](https://github.com/ehmicky/get-node) and the [`nodePath`](../readme.md#optionsnodepath) option can be used to run a specific Node.js version. Alternatively, [`nvexeca`](https://github.com/ehmicky/nvexeca) or [`nve`](https://github.com/ehmicky/nve) can be used.
```jsimport {execaNode} from 'execa';import getNode from 'get-node';
const {path: nodePath} = await getNode('16.2.0');await execaNode('file.js', {nodePath});```
<hr>
[**Next**: 🌐 Environment](environment.md)\[**Previous**: 📜 Scripts](scripts.md)\[**Top**: Table of contents](../readme.md#documentation)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>6+7+# 📢 Output8+9+## Stdout and stderr10+11+The [`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).12+13+```js14+import {execa} from 'execa';15+16+const {stdout, stderr} = await execa`npm run build`;17+console.log(stdout);18+console.log(stderr);19+```20+21+## Ignore output22+23+```js24+const {stdout, stderr} = await execa({stdout: 'ignore'})`npm run build`;25+console.log(stdout); // undefined26+console.log(stderr); // string with errors27+```28+29+## File output30+31+```js32+await execa({stdout: {file: './output.txt'}})`npm run build`;33+// Or:34+await execa({stdout: new URL('file:///path/to/output.txt')})`npm run build`;35+```36+37+## Terminal output38+39+The 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.40+41+```js42+await execa({stdout: 'inherit', stderr: 'inherit'})`npm run build`;43+```44+45+To 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).46+47+```js48+// Print both stdout/stderr to the parent stdout49+await execa({stdout: process.stdout, stderr: process.stdout})`npm run build`;50+// Or:51+await execa({stdout: 1, stderr: 1})`npm run build`;52+```53+54+## Multiple targets55+56+The 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.57+58+The 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).59+60+```js61+const {stdout} = await execa({stdout: ['inherit', {file: './output.txt'}, 'pipe']})`npm run build`;62+console.log(stdout);63+```64+65+When 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.66+67+## Interleaved output68+69+If 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)72+73+`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.74+75+For example, this prints `1 3 2` instead of `1 2 3` because both `console.log()` are merged into a single write.76+77+```js78+const {all} = await execa({all: true})`node example.js`;79+```80+81+```js82+// example.js83+console.log('1'); // writes to stdout84+console.error('2'); // writes to stderr85+console.log('3'); // writes to stdout86+```87+88+This can be worked around by using `setTimeout()`.89+90+```js91+import {setTimeout} from 'timers/promises';92+93+console.log('1');94+console.error('2');95+await setTimeout(0);96+console.log('3');97+```98+99+## Stdout/stderr-specific options100+101+Some 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.102+103+```js104+// Same value for stdout and stderr105+await execa({verbose: 'full'})`npm run build`;106+107+// Different values for stdout and stderr108+await execa({verbose: {stdout: 'none', stderr: 'full'}})`npm run build`;109+```110+111+## Additional file descriptors112+113+The [`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.114+115+[`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).116+117+```js118+// Retrieve output from file descriptor number 3119+const {stdio} = await execa({120+ stdio: ['pipe', 'pipe', 'pipe', 'pipe'],121+})`npm run build`;122+console.log(stdio[3]);123+```124+125+## Shortcut126+127+The [`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.128+129+```js130+await execa({stdio: 'ignore'})`npm run build`;131+// Same as:132+await execa({stdin: 'ignore', stdout: 'ignore', stderr: 'ignore'})`npm run build`;133+```134+135+## Big output136+137+To prevent high memory consumption, a maximum output size can be set using the [`maxBuffer`](../readme.md#optionsmaxbuffer) option. It defaults to 100MB.138+139+When 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).140+141+This 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.146+147+```js148+try {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+ }156+157+ throw error;158+}159+```160+161+## Low memory162+163+When 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.164+165+This 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.166+167+<hr>168+169+[**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>6+7+# 🔀 Piping multiple subprocesses8+9+## Array syntax10+11+A 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).12+13+```js14+import {execa} from 'execa';15+16+// Similar to `npm run build | head -n 2` in shells17+const {stdout} = await execa('npm', ['run', 'build'])18+ .pipe('head', ['-n', '2']);19+```20+21+## Template string syntax22+23+```js24+const {stdout} = await execa`npm run build`25+ .pipe`head -n 2`;26+```27+28+## Advanced syntax29+30+```js31+const subprocess = execa`head -n 2`;32+const {stdout} = await execa`npm run build`33+ .pipe(subprocess);34+```35+36+## Options37+38+[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.39+40+```js41+const {stdout} = await execa('npm', ['run', 'build'], subprocessOptions)42+ .pipe('head', ['-n', '2'], subprocessOrPipeOptions);43+```44+45+```js46+const {stdout} = await execa(subprocessOptions)`npm run build`47+ .pipe(subprocessOrPipeOptions)`head -n 2`;48+```49+50+```js51+const subprocess = execa(subprocessOptions)`head -n 2`;52+const {stdout} = await execa(subprocessOptions)`npm run build`53+ .pipe(subprocess, pipeOptions);54+```55+56+## Result57+58+When 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.59+60+```js61+const destinationResult = await execa`npm run build`62+ .pipe`head -n 2`;63+console.log(destinationResult.stdout); // First 2 lines of `npm run build`64+65+const sourceResult = destinationResult.pipedFrom[0];66+console.log(sourceResult.stdout); // Full output of `npm run build`67+```68+69+## Errors70+71+When 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.72+73+```js74+try {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+ }87+88+ throw error;89+}90+```91+92+## Series of subprocesses93+94+```js95+await execa`npm run build`96+ .pipe`sort`97+ .pipe`head -n 2`;98+```99+100+## 1 source, multiple destinations101+102+```js103+const subprocess = execa`npm run build`;104+const [sortedResult, truncatedResult] = await Promise.all([105+ subprocess.pipe`sort`,106+ subprocess.pipe`head -n 2`,107+]);108+```109+110+## Multiple sources, 1 destination111+112+```js113+const destination = execa`./log-remotely.js`;114+await Promise.all([115+ execa`npm run build`.pipe(destination),116+ execa`npm run test`.pipe(destination),117+]);118+```119+120+## Source file descriptor121+122+By default, the source's [`stdout`](../readme.md#subprocessstdout) is used, but this can be changed using the [`from`](../readme.md#pipeoptionsfrom) piping option.123+124+```js125+await execa`npm run build`126+ .pipe({from: 'stderr'})`head -n 2`;127+```128+129+## Destination file descriptor130+131+By default, the destination's [`stdin`](../readme.md#subprocessstdin) is used, but this can be changed using the [`to`](../readme.md#pipeoptionsto) piping option.132+133+```js134+await execa`npm run build`135+ .pipe({to: 'fd3'})`./log-remotely.js`;136+```137+138+## Unpipe139+140+Piping can be stopped using the [`unpipeSignal`](../readme.md#pipeoptionsunpipesignal) piping option.141+142+The [`subprocess.pipe()`](../readme.md#subprocesspipefile-arguments-options) method will be rejected with a cancelation error. However, each subprocess will keep running.143+144+```js145+const abortController = new AbortController();146+147+process.on('SIGUSR1', () => {148+ abortController.abort();149+});150+151+// If the process receives SIGUSR1, `npm run build` stopped being logged remotely.152+// However, it keeps running successfully.153+try {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+```162+163+<hr>164+165+[**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>6 3-With 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+# 📜 Scripts8 9+## Script files10+11+[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.12+13+Scripts 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).14+15+[More info about the difference between Execa, Bash and zx.](bash.md)16+17 ```js18 import {$} from 'execa';19 20 const {stdout: name} = await $`cat package.json`8 unmodified lines29 $`sleep 2`,30 $`sleep 3`,31 ]);32 27-const dirName = 'foo bar';28-await $`mkdir /tmp/${dirName}`;33+const directoryName = 'foo bar';34+await $`mkdir /tmp/${directoryName}`;35 ```36 37 ## Template string syntax38 33-The 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?)`.39+Just 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).40 35-Also, 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.41+Conversely, 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).42 37-The only difference between `$` and `execa` is that the former includes [script-friendly default options](../readme.md#file-arguments-options).38-43 ```js44 import {execa, $} from 'execa';45 46 const branch = await execa`git branch --show-current`;47 await $('dep', ['deploy', `--branch=${branch}`]);48 ```49 46-## Examples50+<hr>51 48-### Main binary49-50-```sh51-# Bash52-bash file.sh53-```54-55-```js56-// zx57-zx file.js58-59-// or a shebang can be used:60-// #!/usr/bin/env zx61-```62-63-```js64-// Execa scripts are just regular Node.js files65-node file.js66-```67-68-### Global variables69-70-```js71-// zx72-await $`echo example`;73-```74-75-```js76-// Execa77-import {$} from 'execa';78-79-await $`echo example`;80-```81-82-### Command execution83-84-```sh85-# Bash86-echo example87-```88-89-```js90-// zx91-await $`echo example`;92-```93-94-```js95-// Execa96-await $`echo example`;97-```98-99-### Multiline commands100-101-```sh102-# Bash103-npm run build \104- --example-flag-one \105- --example-flag-two106-```107-108-```js109-// zx110-await $`npm run build ${[111- '--example-flag-one',112- '--example-flag-two',113-]}`;114-```115-116-```js117-// Execa118-await $`npm run build119- --example-flag-one120- --example-flag-two`121-```122-123-### Concatenation124-125-```sh126-# Bash127-tmpDir="/tmp"128-mkdir "$tmpDir/filename"129-```130-131-```js132-// zx133-const tmpDir = '/tmp'134-await $`mkdir ${tmpDir}/filename`;135-```136-137-```js138-// Execa139-const tmpDir = '/tmp'140-await $`mkdir ${tmpDir}/filename`;141-```142-143-### Variable substitution144-145-```sh146-# Bash147-echo $LANG148-```149-150-```js151-// zx152-await $`echo $LANG`;153-```154-155-```js156-// Execa157-await $`echo ${process.env.LANG}`;158-```159-160-### Escaping161-162-```sh163-# Bash164-echo 'one two'165-```166-167-```js168-// zx169-await $`echo ${'one two'}`;170-```171-172-```js173-// Execa174-await $`echo ${'one two'}`;175-```176-177-### Escaping multiple arguments178-179-```sh180-# Bash181-echo 'one two' '$'182-```183-184-```js185-// zx186-await $`echo ${['one two', '$']}`;187-```188-189-```js190-// Execa191-await $`echo ${['one two', '$']}`;192-```193-194-### Subcommands195-196-```sh197-# Bash198-echo "$(echo example)"199-```200-201-```js202-// zx203-const example = await $`echo example`;204-await $`echo ${example}`;205-```206-207-```js208-// Execa209-const example = await $`echo example`;210-await $`echo ${example}`;211-```212-213-### Serial commands214-215-```sh216-# Bash217-echo one && echo two218-```219-220-```js221-// zx222-await $`echo one && echo two`;223-```224-225-```js226-// Execa227-await $`echo one`;228-await $`echo two`;229-```230-231-### Parallel commands232-233-```sh234-# Bash235-echo one &236-echo two &237-```238-239-```js240-// zx241-await Promise.all([$`echo one`, $`echo two`]);242-```243-244-```js245-// Execa246-await Promise.all([$`echo one`, $`echo two`]);247-```248-249-### Global/shared options250-251-```sh252-# Bash253-options="timeout 5"254-$options echo one255-$options echo two256-$options echo three257-```258-259-```js260-// zx261-const timeout = '5s';262-await $`echo one`.timeout(timeout);263-await $`echo two`.timeout(timeout);264-await $`echo three`.timeout(timeout);265-```266-267-```js268-// Execa269-import {$ as $_} from 'execa';270-271-const $ = $_({timeout: 5000});272-273-await $`echo one`;274-await $`echo two`;275-await $`echo three`;276-```277-278-### Environment variables279-280-```sh281-# Bash282-EXAMPLE=1 example_command283-```284-285-```js286-// zx287-$.env.EXAMPLE = '1';288-await $`example_command`;289-delete $.env.EXAMPLE;290-```291-292-```js293-// Execa294-await $({env: {EXAMPLE: '1'}})`example_command`;295-```296-297-### Local binaries298-299-```sh300-# Bash301-npx tsc --version302-```303-304-```js305-// zx306-await $`npx tsc --version`;307-```308-309-```js310-// Execa311-await $`tsc --version`;312-```313-314-### Builtin utilities315-316-```js317-// zx318-const content = await stdin();319-```320-321-```js322-// Execa323-import getStdin from 'get-stdin';324-325-const content = await getStdin();326-```327-328-### Printing to stdout329-330-```sh331-# Bash332-echo example333-```334-335-```js336-// zx337-echo`example`;338-```339-340-```js341-// Execa342-console.log('example');343-```344-345-### Silent stderr346-347-```sh348-# Bash349-echo example 2> /dev/null350-```351-352-```js353-// zx354-await $`echo example`.stdio('inherit', 'pipe', 'ignore');355-```356-357-```js358-// Execa does not print stdout/stderr by default359-await $`echo example`;360-```361-362-### Verbose mode363-364-```sh365-# Bash366-set -v367-echo example368-```369-370-```js371-// zx >=8372-await $`echo example`.verbose();373-374-// or:375-$.verbose = true;376-```377-378-```js379-// Execa380-import {$ as $_} from 'execa';381-382-// `verbose: 'short'` is also available383-const $ = $_({verbose: 'full'});384-385-await $`echo example`;386-```387-388-Or:389-390-```391-NODE_DEBUG=execa node file.js392-```393-394-Which prints:395-396-```397-[19:49:00.360] [0] $ echo example398-example399-[19:49:00.383] [0] √ (done in 23ms)400-```401-402-### Piping stdout to another command403-404-```sh405-# Bash406-echo npm run build | sort | head -n2407-```408-409-```js410-// zx411-await $`npm run build | sort | head -n2`;412-```413-414-```js415-// Execa416-await $`npm run build`417- .pipe`sort`418- .pipe`head -n2`;419-```420-421-### Piping stdout and stderr to another command422-423-```sh424-# Bash425-echo example |& cat426-```427-428-```js429-// zx430-const echo = $`echo example`;431-const cat = $`cat`;432-echo.pipe(cat)433-echo.stderr.pipe(cat.stdin);434-await Promise.all([echo, cat]);435-```436-437-```js438-// Execa439-await $({all: true})`echo example`440- .pipe({from: 'all'})`cat`;441-```442-443-### Piping stdout to a file444-445-```sh446-# Bash447-echo example > file.txt448-```449-450-```js451-// zx452-await $`echo example`.pipe(fs.createWriteStream('file.txt'));453-```454-455-```js456-// Execa457-await $({stdout: {file: 'file.txt'}})`echo example`;458-```459-460-### Piping stdin from a file461-462-```sh463-# Bash464-echo example < file.txt465-```466-467-```js468-// zx469-const cat = $`cat`470-fs.createReadStream('file.txt').pipe(cat.stdin)471-await cat472-```473-474-```js475-// Execa476-await $({inputFile: 'file.txt'})`cat`477-```478-479-### Iterate over output lines480-481-```sh482-# Bash483-while read484-do485- if [[ "$REPLY" == *ERROR* ]]486- then487- echo "$REPLY"488- fi489-done < <(npm run build)490-```491-492-```js493-// zx does not allow proper iteration.494-// For example, the iteration does not handle subprocess errors.495-```496-497-```js498-// Execa499-for await (const line of $`npm run build`) {500- if (line.includes('ERROR')) {501- console.log(line);502- }503-}504-```505-506-### Errors507-508-```sh509-# Bash communicates errors only through the exit code and stderr510-timeout 1 sleep 2511-echo $?512-```513-514-```js515-// zx516-const {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-```543-544-```js545-// Execa546-const {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-```585-586-### Exit codes587-588-```sh589-# Bash590-false591-echo $?592-```593-594-```js595-// zx596-const {exitCode} = await $`false`.nothrow();597-echo`${exitCode}`;598-```599-600-```js601-// Execa602-const {exitCode} = await $({reject: false})`false`;603-console.log(exitCode);604-```605-606-### Timeouts607-608-```sh609-# Bash610-timeout 5 echo example611-```612-613-```js614-// zx615-await $`echo example`.timeout('5s');616-```617-618-```js619-// Execa620-await $({timeout: 5000})`echo example`;621-```622-623-### Current filename624-625-```sh626-# Bash627-echo "$(basename "$0")"628-```629-630-```js631-// zx632-await $`echo ${__filename}`;633-```634-635-```js636-// Execa637-import {fileURLToPath} from 'node:url';638-import path from 'node:path';639-640-const __filename = path.basename(fileURLToPath(import.meta.url));641-642-await $`echo ${__filename}`;643-```644-645-### Current directory646-647-```sh648-# Bash649-cd project650-```651-652-```js653-// zx654-cd('project');655-656-// or:657-$.cwd = 'project';658-```659-660-```js661-// Execa662-const $$ = $({cwd: 'project'});663-```664-665-### Multiple current directories666-667-```sh668-# Bash669-pushd project670-pwd671-popd672-pwd673-```674-675-```js676-// zx677-within(async () => {678- cd('project');679- await $`pwd`;680-});681-682-await $`pwd`;683-```684-685-```js686-// Execa687-await $({cwd: 'project'})`pwd`;688-await $`pwd`;689-```690-691-### Background subprocesses692-693-```sh694-# Bash695-echo one &696-```697-698-```js699-// zx does not allow setting the `detached` option700-```701-702-```js703-// Execa704-await $({detached: true})`echo one`;705-```706-707-### IPC708-709-```sh710-# Bash does not allow simple IPC711-```712-713-```js714-// zx does not allow simple IPC715-```716-717-```js718-// Execa719-const subprocess = $({ipc: true})`node script.js`;720-721-subprocess.on('message', message => {722- if (message === 'ping') {723- subprocess.send('pong');724- }725-});726-```727-728-### Transforms729-730-```sh731-# Bash does not allow transforms732-```733-734-```js735-// zx does not allow transforms736-```737-738-```js739-// Execa740-const transform = function * (line) {741- if (!line.includes('secret')) {742- yield line;743- }744-};745-746-await $({stdout: [transform, 'inherit']})`echo ${'This is a secret.'}`;747-```748-749-### Cancellation750-751-```sh752-# Bash753-kill $PID754-```755-756-```js757-// zx758-subprocess.kill();759-```760-761-```js762-// Execa763-// Can specify an error message and stack trace764-subprocess.kill(error);765-766-// Or use an `AbortSignal`767-const controller = new AbortController();768-await $({signal: controller.signal})`node long-script.js`;769-```770-771-### Interleaved output772-773-```sh774-# Bash prints stdout and stderr interleaved775-```776-777-```js778-// zx separates stdout and stderr779-const {stdout, stderr} = await $`node example.js`;780-```781-782-```js783-// Execa can interleave stdout and stderr784-const {all} = await $({all: true})`node example.js`;785-```786-787-### PID788-789-```sh790-# Bash791-echo example &792-echo $!793-```794-795-```js796-// zx does not return `subprocess.pid`797-```798-799-```js800-// Execa801-const {pid} = $`echo example`;802-```803-804-## Differences with Bash and zx805-806-This section describes the differences between Bash, Execa, and [zx](https://github.com/google/zx) (which inspired this feature).807-808-### Flexibility809-810-Unlike 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).811-812-### Shell813-814-The 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.815-816-This is more cross-platform. For example, your code works the same on Windows machines without Bash installed.817-818-Also, there is no shell syntax to remember: everything is just plain JavaScript.819-820-If you really need a shell though, the [`shell`](../readme.md#optionsshell) option can be used.821-822-### Simplicity823-824-Execa's scripting API mostly consists of only two methods: [`` $`command` ``](../readme.md#file-arguments-options) and [`$(options)`](../readme.md#execaoptions).825-826-[No special binary](#main-binary) is recommended, no [global variable](#global-variables) is injected: scripts are regular Node.js files.827-828-Execa 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.829-830-### Modularity831-832-zx includes many builtin utilities: `fetch()`, `question()`, `sleep()`, `stdin()`, `retry()`, `spinner()`, `chalk`, `fs-extra`, `os`, `path`, `globby`, `yaml`, `minimist`, `which`, Markdown scripts, remote scripts.833-834-Execa 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.835-836-### Performance837-838-Spawning a shell for every command comes at a performance cost, which Execa avoids.839-840-Also, [local binaries](#local-binaries) can be directly executed without using `npx`.841-842-### Debugging843-844-Subprocesses can be hard to debug, which is why Execa includes a [`verbose`](#verbose-mode) option.845-846-Also, 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).847-848-Finally, 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
1234567891011121314151617181920212223242526272829303132333435363738<picture> <source media="(prefers-color-scheme: dark)" srcset="../media/logo_dark.svg"> <img alt="execa logo" src="../media/logo.svg" width="400"></picture><br>
# 💻 Shell
## Avoiding shells
In general, [shells](https://en.wikipedia.org/wiki/Shell_(computing)) should be avoided because they are:- Not cross-platform, encouraging shell-specific syntax.- Slower, because of the additional shell interpretation.- Unsafe, potentially allowing [command injection](https://en.wikipedia.org/wiki/Code_injection#Shell_injection) (see the [escaping section](escaping.md#shells)).
## Specific shell
```jsimport {execa} from 'execa';
await execa({shell: '/bin/bash'})`npm run "$TASK" && npm run test`;```
## OS-specific shell
When the [`shell`](../readme.md#optionsshell) option is `true`, `sh` is used on Unix and [`cmd.exe`](https://en.wikipedia.org/wiki/Cmd.exe) is used on Windows.
`sh` and `cmd.exe` syntaxes are very different. Therefore, this is usually not useful.
```jsawait execa({shell: true})`npm run build`;```
<hr>
[**Next**: 📜 Scripts](scripts.md)\[**Previous**: 💬 Escaping/quoting](escaping.md)\[**Top**: Table of contents](../readme.md#documentation)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>6+7+# ⏳️ Streams8+9+## Node.js streams10+11+### Input12+13+```js14+import {createReadStream} from 'node:fs';15+import {once} from 'node:events';16+import {execa} from 'execa';17+18+const readable = createReadStream('./input.txt');19+await once(readable, 'open');20+await execa({stdin: readable})`npm run scaffold`;21+```22+23+### Output24+25+```js26+import {createWriteStream} from 'node:fs';27+import {once} from 'node:events';28+import {execa} from 'execa';29+30+const writable = createWriteStream('./output.txt');31+await once(writable, 'open');32+await execa({stdout: writable})`npm run build`;33+```34+35+### File descriptors36+37+When 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.38+39+```40+TypeError [ERR_INVALID_ARG_VALUE]: The argument 'stdio' is invalid.41+```42+43+This 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`.47+48+## Web streams49+50+[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).51+52+```js53+const response = await fetch('https://example.com');54+await execa({stdin: response.body})`npm run build`;55+```56+57+## Iterables as input58+59+```js60+const getReplInput = async function * () {61+ for await (const replLine of getReplLines()) {62+ yield replLine;63+ }64+};65+66+await execa({stdin: getReplInput()})`npm run scaffold`;67+```68+69+## Manual streaming70+71+[`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.72+73+They 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).78+79+## Converting a subprocess to a stream80+81+### Convert82+83+The [`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.84+85+This 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.86+87+```js88+const readable = execa`npm run scaffold`.readable();89+90+const writable = execa`npm run scaffold`.writable();91+92+const duplex = execa`npm run scaffold`.duplex();93+```94+95+### Different file descriptor96+97+By 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.98+99+```js100+const readable = execa`npm run scaffold`.readable({from: 'stderr'});101+102+const writable = execa`npm run scaffold`.writable({to: 'fd3'});103+104+const duplex = execa`npm run scaffold`.duplex({from: 'stderr', to: 'fd3'});105+```106+107+### Error handling108+109+When 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.110+111+This 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.112+113+<hr>114+115+[**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>6+7+# 🏁 Termination8+9+## Canceling10+11+The [`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.12+13+```js14+import {execa} from 'execa';15+16+const abortController = new AbortController();17+18+setTimeout(() => {19+ abortController.abort();20+}, 5000);21+22+try {23+ await execa({cancelSignal: abortController.signal})`npm run build`;24+} catch (error) {25+ if (error.isCanceled) {26+ console.error('Aborted by cancelSignal.');27+ }28+29+ throw error;30+}31+```32+33+## Timeout34+35+If the subprocess lasts longer than the [`timeout`](../readme.md#optionstimeout) option, a [`SIGTERM` signal](#default-signal) is sent to it.36+37+```js38+try {39+ await execa({timeout: 5000})`npm run build`;40+} catch (error) {41+ if (error.timedOut) {42+ console.error('Timed out.');43+ }44+45+ throw error;46+}47+```48+49+## Current process exit50+51+If 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.55+56+## Signal termination57+58+[`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.59+60+[More info.](https://nodejs.org/api/child_process.html#subprocesskillsignal)61+62+### SIGTERM63+64+[`SIGTERM`](https://en.wikipedia.org/wiki/Signal_(IPC)#SIGTERM) is the default signal. It terminates the subprocess.65+66+```js67+const subprocess = execa`npm run build`;68+subprocess.kill();69+// Is the same as:70+subprocess.kill('SIGTERM');71+```72+73+The subprocess can [handle that signal](https://nodejs.org/api/process.html#process_signal_events) to run some cleanup logic.74+75+```js76+process.on('SIGTERM', () => {77+ cleanup();78+ process.exit(1);79+})80+```81+82+### SIGKILL83+84+[`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.85+86+```js87+subprocess.kill('SIGKILL');88+```89+90+### Other signals91+92+Other 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).93+94+### Default signal95+96+The [`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.97+98+```js99+const subprocess = execa({killSignal: 'SIGKILL'})`npm run build`;100+subprocess.kill(); // Forceful termination101+```102+103+### Signal name and description104+105+When a subprocess was terminated by a signal, [`error.isTerminated`](../readme.md#resultisterminated) is `true`.106+107+Also, [`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).108+109+```js110+try {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+ }117+118+ throw error;119+}120+```121+122+## Forceful termination123+124+If the subprocess is terminated but does not exit, [`SIGKILL`](#sigkill) is automatically sent to forcefully terminate it.125+126+The grace period is set by the [`forceKillAfterDelay`](../readme.md#optionsforcekillafterdelay) option, which is 5 seconds by default. This feature can be disabled with `false`.127+128+This 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.131+132+This 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).136+137+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.138+139+```js140+// No forceful termination141+const subprocess = execa({forceKillAfterDelay: false})`npm run build`;142+subprocess.kill();143+```144+145+## Inter-process termination146+147+[`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.148+149+```js150+const subprocess = execa`npm run build`;151+console.log('PID:', subprocess.pid); // PID: 6513152+await subprocess;153+```154+155+```sh156+$ kill -SIGTERM 6513157+```158+159+## Error message and stack trace160+161+When 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).162+163+```js164+try {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+ }176+177+ throw error;178+}179+```180+181+<hr>182+183+[**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>6 7+# 🧙 Transforms8+9 ## Summary10 5-Transforms 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*).11+Transforms 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*).12 13 ```js14 import {execa} from 'execa';15 1 unmodified line17 const prefix = line.includes('error') ? 'ERROR' : 'INFO';18 yield `${prefix}: ${line}`;19 };20 15-const {stdout} = await execa('./run.js', {stdout: transform});21+const {stdout} = await execa({stdout: transform})`npm run build`;22 console.log(stdout); // HELLO23 ```24 19-## Encoding25+## Difference with iteration26 21-The `line` argument passed to the transform is a string by default.\22-However, if the [`binary`](#transformoptionsbinary) transform option is `true` or if the [`encoding`](../readme.md#optionsencoding) subprocess option is binary, it is an `Uint8Array` instead.27+Transforms 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).31 24-The transform can `yield` either a `string` or an `Uint8Array`, regardless of the `line` argument's type.25-32 ## Filtering33 34 `yield` can be called 0, 1 or multiple times. Not calling `yield` enables filtering a specific line.35 36 ```js31-import {execa} from 'execa';32-37 const transform = function * (line) {38 if (!line.includes('secret')) {39 yield line;40 }41 };42 39-const {stdout} = await execa('echo', ['This is a secret.'], {stdout: transform});43+const {stdout} = await execa({stdout: transform})`echo ${'This is a secret'}`;44 console.log(stdout); // ''45 ```46 43-## Binary data44-45-The transform iterates over lines by default.\46-However, 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.47-48-```js49-await execa('./binary.js', {stdout: {transform, binary: true}});50-```51-52-This 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.55-56-## Newlines57-58-Unless the [`binary`](#transformoptionsbinary) transform option is `true`, the transform iterates over lines.59-By default, newlines are stripped from each `line` argument.60-61-```js62-// `line`'s value never ends with '\n'.63-const transform = function * (line) { /* ... */ };64-65-await execa('./run.js', {stdout: transform});66-```67-68-However, if the [`preserveNewlines`](#transformoptionspreservenewlines) transform option is `true`, newlines are kept.69-70-```js71-// `line`'s value ends with '\n'.72-// The output's last `line` might or might not end with '\n', depending on the output.73-const transform = function * (line) { /* ... */ };74-75-await execa('./run.js', {stdout: {transform, preserveNewlines: true}});76-```77-78-Each `yield` produces at least one line. Calling `yield` multiple times or calling `yield *` produces multiples lines.79-80-```js81-const transform = function * (line) {82- yield 'Important note:';83- yield 'Read the comments below.';84-85- // Or:86- yield * [87- 'Important note:',88- 'Read the comments below.',89- ];90-91- // Is the same as:92- yield 'Important note:\nRead the comments below.\n';93-94- yield line95-};96-97-await execa('./run.js', {stdout: transform});98-```99-100-However, if the [`preserveNewlines`](#transformoptionspreservenewlines) transform option is `true`, multiple `yield`s produce a single line instead.101-102-```js103-const transform = function * (line) {104- yield 'Important note: ';105- yield 'Read the comments below.\n';106-107- // Is the same as:108- yield 'Important note: Read the comments below.\n';109-110- yield line111-};112-113-await execa('./run.js', {stdout: {transform, preserveNewlines: true}});114-```115-47 ## Object mode48 118-By default, `stdout` and `stderr`'s transforms must return a string or an `Uint8Array`.\119-However, 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.49+By 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.50 51 ```js52 const transform = function * (line) {53 yield JSON.parse(line);54 };55 126-const {stdout} = await execa('./jsonlines-output.js', {stdout: {transform, objectMode: true}});56+const {stdout} = await execa({stdout: {transform, objectMode: true}})`node jsonlines-output.js`;57 for (const data of stdout) {128- console.log(stdout); // {...}58+ console.log(stdout); // {...object}59 }60 ```61 62 [`stdin`](../readme.md#optionsstdin) can also use `objectMode: true`.3 unmodified lines66 yield JSON.stringify(line);67 };68 69 const input = [{event: 'example'}, {event: 'otherExample'}];140-await execa('./jsonlines-input.js', {stdin: [input, {transform, objectMode: true}]});70+await execa({stdin: [input, {transform, objectMode: true}]})`node jsonlines-input.js`;71 ```72 73 ## Sharing state74 145-State can be shared between calls of the [`transform`](#transformoptionstransform) and [`final`](#transformoptionsfinal) functions.75+State can be shared between calls of the [`transform`](../readme.md#transformoptionstransform) and [`final`](../readme.md#transformoptionsfinal) functions.76 77 ```js148-let count = 078+let count = 0;79 80 // Prefix line number81 const transform = function * (line) {82 yield `[${count++}] ${line}`;1 unmodified line84 ```85 86 ## Finalizing87 158-To create additional lines after the last one, a [`final`](#transformoptionsfinal) generator function can be used.88+To create additional lines after the last one, a [`final`](../readme.md#transformoptionsfinal) generator function can be used.89 90 ```js91 let count = 0;92 5 unmodified lines98 const final = function * () {99 yield `Number of lines: ${count}`;100 };101 172-const {stdout} = await execa('./command.js', {stdout: {transform, final}});102+const {stdout} = await execa({stdout: {transform, final}})`npm run build`;103 console.log(stdout); // Ends with: 'Number of lines: 54'104 ```105 106 ## Duplex/Transform streams107 108 A [`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.109 180-Like 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.110+Like 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.111 182-The [`objectMode`](#object-mode) transform option can be used, but not the [`binary`](#encoding) nor [`preserveNewlines`](#newlines) options.112+The [`objectMode`](#object-mode) transform option can be used, but not the [`binary`](../readme.md#transformoptionsbinary) nor [`preserveNewlines`](../readme.md#transformoptionspreservenewlines) options.113 114 ```js115 import {createGzip} from 'node:zlib';116 import {execa} from 'execa';117 188-const {stdout} = await execa('./run.js', {stdout: {transform: createGzip()}});118+const {stdout} = await execa({119+ stdout: {transform: createGzip()},120+ encoding: 'buffer',121+})`npm run build`;122 console.log(stdout); // `stdout` is compressed with gzip123 ```124 125 ```js193-import {execa} from 'execa';194-195-const {stdout} = await execa('./run.js', {stdout: new CompressionStream('gzip')});126+const {stdout} = await execa({127+ stdout: new CompressionStream('gzip'),128+ encoding: 'buffer',129+})`npm run build`;130 console.log(stdout); // `stdout` is compressed with gzip131 ```132 133 ## Combining134 201-The [`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`.135+The [`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'`.136 137 ```js204-await execa('echo', ['hello'], {stdout: [transform, 'inherit']});138+await execa({stdout: [transform, 'inherit']})`npm run build`;139 ```140 141 This also allows using multiple transforms.142 143 ```js210-await execa('echo', ['hello'], {stdout: [transform, otherTransform]});144+await execa({stdout: [transform, otherTransform]})`npm run build`;145 ```146 213-Or saving to files.147+Or saving to archives.148 149 ```js216-await execa('./run.js', {stdout: [new CompressionStream('gzip'), {file: './output.gz'}]});150+await execa({stdout: [new CompressionStream('gzip'), {file: './output.gz'}]})`npm run build`;151 ```152 219-## Async iteration153+<hr>154 221-In some cases, [iterating](../readme.md#subprocessiterablereadableoptions) over the subprocess can be an alternative to transforms.222-223-```js224-import {execa} from 'execa';225-226-for await (const line of execa('./run.js')) {227- const prefix = line.includes('error') ? 'ERROR' : 'INFO';228- console.log(`${prefix}: ${line}`);229-}230-```231-232-## Transform options233-234-A 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.235-236-A transform is either a [generator function](#transformoptionstransform) or a plain object with the following members.237-238-### transformOptions.transform239-240-Type: `GeneratorFunction<string | Uint8Array | unknown>` | `AsyncGeneratorFunction<string | Uint8Array | unknown>`241-242-Map or [filter](#filtering) the input or output of the subprocess.243-244-More info [here](#summary) and [there](#sharing-state).245-246-### transformOptions.final247-248-Type: `GeneratorFunction<string | Uint8Array | unknown>` | `AsyncGeneratorFunction<string | Uint8Array | unknown>`249-250-Create additional lines after the last one.251-252-[More info.](#finalizing)253-254-### transformOptions.binary255-256-Type: `boolean`\257-Default: `false`258-259-If `true`, iterate over arbitrary chunks of `Uint8Array`s instead of line `string`s.260-261-More info [here](#encoding) and [there](#binary-data).262-263-### transformOptions.preserveNewlines264-265-Type: `boolean`\266-Default: `false`267-268-If `true`, keep newlines in each `line` argument. Also, this allows multiple `yield`s to produces a single line.269-270-[More info.](#newlines)271-272-### transformOptions.objectMode273-274-Type: `boolean`\275-Default: `false`276-277-If `true`, allow [`transformOptions.transform`](#transformoptionstransform) and [`transformOptions.final`](#transformoptionsfinal) to return any type, not just `string` or `Uint8Array`.278-279-[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
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657<picture> <source media="(prefers-color-scheme: dark)" srcset="../media/logo_dark.svg"> <img alt="execa logo" src="../media/logo.svg" width="400"></picture><br>
# 📎 Windows
Although each OS implements subprocesses very differently, Execa makes them cross-platform, except in a few instances.
## Shebang
On Unix, executable files can use [shebangs](https://en.wikipedia.org/wiki/Shebang_(Unix)).
```jsimport {execa} from 'execa';
// If script.js starts with #!/usr/bin/env nodeawait execa`./script.js`;
// Then, the above is a shortcut for:await execa`node ./script.js`;```
Although Windows does not natively support shebangs, Execa adds support for them.
## Signals
Only few [signals](termination.md#other-signals) work on Windows with Node.js: [`SIGTERM`](termination.md#sigterm), [`SIGKILL`](termination.md#sigkill) and [`SIGINT`](https://en.wikipedia.org/wiki/Signal_(IPC)#SIGINT). Also, sending signals from other processes is [not supported](termination.md#signal-name-and-description). Finally, the [`forceKillAfterDelay`](../readme.md#optionsforcekillafterdelay) option [is a noop](termination.md#forceful-termination) on Windows.
## Asynchronous I/O
The default value for the [`stdin`](../readme.md#optionsstdin), [`stdout`](../readme.md#optionsstdout) and [`stderr`](../readme.md#optionsstderr) options is [`'pipe'`](output.md#stdout-and-stderr). This returns the output as [`result.stdout`](../readme.md#resultstdout) and [`result.stderr`](../readme.md#resultstderr) and allows for [manual streaming](streams.md#manual-streaming).
Instead of `'pipe'`, `'overlapped'` can be used instead to use [asynchronous I/O](https://learn.microsoft.com/en-us/windows/win32/fileio/synchronous-and-asynchronous-i-o) under-the-hood on Windows, instead of the default behavior which is synchronous. On other platforms, asynchronous I/O is always used, so `'overlapped'` behaves the same way as `'pipe'`.
## `cmd.exe` escaping
If the [`windowsVerbatimArguments`](../readme.md#optionswindowsverbatimarguments) option is `false`, the [command arguments](input.md#command-arguments) are automatically escaped on Windows. When using a [`cmd.exe`](https://en.wikipedia.org/wiki/Cmd.exe) [shell](../readme.md#optionsshell), this is `true` by default instead.
This is ignored on other platforms: those are [automatically escaped](escaping.md) by default.
## Console window
If the [`windowsHide`](../readme.md#optionswindowshide) option is `false`, the subprocess is run in a new console window. This is necessary to make [`SIGINT` work](https://github.com/nodejs/node/issues/29837) on Windows, and to prevent subprocesses not being cleaned up in [some specific situations](https://github.com/sindresorhus/execa/issues/433).
## UID and GID
By default, subprocesses are run using the current [user](https://en.wikipedia.org/wiki/User_identifier) and [group](https://en.wikipedia.org/wiki/Group_identifier). The [`uid`](../readme.md#optionsuid) and [`gid`](../readme.md#optionsgid) options can be used to set a different user or group.
However, since Windows uses a different permission model, those options throw.
<hr>
[**Next**: 🔍 Differences with Bash and zx](bash.md)\[**Previous**: 🐛 Debugging](debugging.md)\[**Top**: Table of contents](../readme.md#documentation)modified:lib/pipe/abort.js+1 added-1 removed
8 unmodified lines9 10 const 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 linesmodified:test/pipe/abort.js+1 added-1 removed
24 unmodified lines25 t.is(error.all, undefined);26 t.deepEqual(error.stdio, Array.from({length: error.stdio.length}));27 t.deepEqual(error.pipedFrom, []);28 29- 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 linesmodified:types/arguments/options.d.ts+48 added-118 removed
6 unmodified lines7 export type CommonOptions<IsSync extends boolean = boolean> = {8 /**9 Prefer locally installed binaries when looking for a binary to execute.10 11- If you `$ npm install foo`, you can then `execa('foo')`.12-11 @default `true` with `$`, `false` otherwise12 */13 readonly preferLocal?: boolean;14 15 /**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.17 20- @default process.cwd()18+ @default `cwd` option19 */20 readonly localDir?: string | URL;21 22 /**5 unmodified lines28 29 /**30 Path to the Node.js executable.31 34- For example, this can be used together with [`get-node`](https://github.com/ehmicky/get-node) to run a specific Node.js version.35-32 Requires the `node` option to be `true`.33 34 @default [`process.execPath`](https://nodejs.org/api/process.html#process_process_execpath) (current Node.js executable)35 */36 readonly nodePath?: string | URL;37 38 /**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.40 41 Requires the `node` option to be `true`.42 43 @default [`process.execArgv`](https://nodejs.org/api/process.html#process_process_execargv) (current Node.js CLI options)44 */45 readonly nodeOptions?: readonly string[];46 47 /**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)).49 50 See also the `inputFile` and `stdin` options.51 */52 readonly input?: string | Uint8Array | Readable;53 54 /**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)).56 57 See also the `input` and `stdin` options.58 */59 readonly inputFile?: string | URL;60 61 /**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`.63 79- 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']`.65 81- 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)82-83- @default `inherit` with `$`, `pipe` otherwise66+ @default `'inherit'` with `$`, `'pipe'` otherwise67 */68 readonly stdin?: StdinOptionCommon<IsSync>;69 70 /**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`.72 99- 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']`.74 101- 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)102-75 @default 'pipe'76 */77 readonly stdout?: StdoutStderrOptionCommon<IsSync>;78 79 /**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`.81 119- 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']`.83 121- 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)122-84 @default 'pipe'85 */86 readonly stderr?: StdoutStderrOptionCommon<IsSync>;87 88 /**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'}`.90 130- 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.92 132- 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`.94 95 @default 'pipe'96 */97 readonly stdio?: StdioOptionsProperty<IsSync>;9 unmodified lines107 */108 readonly lines?: FdGenericOption<boolean>;109 110 /**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.112 113 @default true114 */115 readonly reject?: boolean;17 unmodified lines133 */134 readonly extendEnv?: boolean;135 136 /**176- Current working directory of the subprocess.137+ Current [working directory](https://en.wikipedia.org/wiki/Working_directory) of the subprocess.138 139 This is also used to resolve the `nodePath` option when it is a relative path.140 141 @default process.cwd()142 */143 readonly cwd?: string | URL;144 145 /**185- Environment key-value pairs.146+ [Environment variables](https://en.wikipedia.org/wiki/Environment_variable).147 148 Unless the `extendEnv` option is `false`, the subprocess also uses the current process' environment variables ([`process.env`](https://nodejs.org/api/process.html#processenv)).149 189- @default process.env150+ @default [process.env](https://nodejs.org/api/process.html#processenv)151 */152 readonly env?: NodeJS.ProcessEnv;153 154 /**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.156+157+ @default file being executed158 */159 readonly argv0?: string;160 161 /**199- Sets the user identity of the subprocess.162+ Sets the [user identifier](https://en.wikipedia.org/wiki/User_identifier) of the subprocess.163+164+ @default current user identifier165 */166 readonly uid?: number;167 168 /**204- Sets the group identity of the subprocess.169+ Sets the [group identifier](https://en.wikipedia.org/wiki/Group_identifier) of the subprocess.170+171+ @default current group identifier172 */173 readonly gid?: number;174 175 /**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)).177 211- 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.179 180+ We recommend against using this option.181+182 @default false183 */184 readonly shell?: boolean | string | URL;185 186 /**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).188 189 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.192 193 The output is available with `result.stdout`, `result.stderr` and `result.stdio`.194 195 @default 'utf8'2 unmodified lines198 199 /**200 If `timeout` is greater than `0`, the subprocess will be terminated if it runs for longer than that amount of milliseconds.201 202+ On timeout, `result.timedOut` becomes `true`.203+204 @default 0205 */206 readonly timeout?: number;207 208 /**209 Largest amount of data allowed on `stdout`, `stderr` and `stdio`.210 243- When this threshold is hit, the subprocess fails and `error.isMaxBuffer` becomes `true`.244-245- 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.250-211 By default, this applies to both `stdout` and `stderr`, but different values can also be passed.212 213 @default 100_000_000214 */215 readonly maxBuffer?: FdGenericOption<number>;216 217 /**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.219 262- 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`).221 222 @default 'SIGTERM'223 */224 readonly killSignal?: string | number;225 226 /**227 If the subprocess is terminated but does not exit, forcefully exit it by sending [`SIGKILL`](https://en.wikipedia.org/wiki/Signal_(IPC)#SIGKILL).228 271- The grace period is 5 seconds by default. This feature can be disabled with `false`.272-273- This works when the subprocess is terminated by either:274- - the `cancelSignal`, `timeout`, `maxBuffer` or `cleanup` option275- - calling `subprocess.kill()` with no arguments276-277- 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 process281-282- 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.283-229 @default 5000230 */231 readonly forceKillAfterDelay?: Unless<IsSync, number | false>;232 233 /**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.235 291- @default false236+ @default `true` if the `shell` option is `true`, `false` otherwise237 */238 readonly windowsVerbatimArguments?: boolean;239 240 /**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.242 243 @default true244 */245 readonly windowsHide?: boolean;246 247 /**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.249 305- 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.251 310- This can also be set to `'full'` by setting the `NODE_DEBUG=execa` environment variable in the current process.311-252 By default, this applies to both `stdout` and `stderr`, but different values can also be passed.253 254 @default 'none'255 */256 readonly verbose?: FdGenericOption<'none' | 'short' | 'full'>;257 258 /**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.260 261 @default true262 */263 readonly cleanup?: Unless<IsSync, boolean>;264 265 /**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.267 330- On failure, the `error.stdout`, `error.stderr`, `error.all` and `error.stdio` properties are used instead.331-332- 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.333-268 By default, this applies to both `stdout` and `stderr`, but different values can also be passed.269 270 @default true271 */272 readonly buffer?: FdGenericOption<boolean>;273 274 /**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`.276 277 @default false278 */279 readonly all?: boolean;5 unmodified lines285 */286 readonly ipc?: Unless<IsSync, boolean>;287 288 /**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.290 359- [More info.](https://nodejs.org/api/child_process.html#child_process_advanced_serialization)360-291 @default 'advanced'292 */293 readonly serialization?: Unless<IsSync, 'json' | 'advanced'>;294 295 /**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.297 298 @default false299 */300 readonly detached?: Unless<IsSync, boolean>;60 unmodified linesmodified:types/methods/command.d.ts+1 added-14 removed
13 unmodified lines14 ): ExecaSubprocess<OptionsType & NewOptionsType>;15 };16 17 /**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.18+Executes a command. `command` is a string that includes both the `file` and its `arguments`.19 20 This is only intended for very specific cases, such as a REPL. This should be avoided otherwise.21 22 Just like `execa()`, this can bind options. It can also be run synchronously using `execaCommandSync()`.23 24-Arguments are automatically escaped. They can contain any character, but spaces must be escaped with a backslash like `execaCommand('echo has\\ space')`.25-24 @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 lines53 Same as `execaCommand()` but synchronous.54 55 Returns or throws a subprocess `result`. The `subprocess` is not returned: its methods and properties are not available.56 59-The 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.69-57 @param command - The program/script to execute and its arguments.58 @returns A subprocess `result` object59 @throws A subprocess `result` error60 10 unmodified linesmodified:types/methods/main-async.d.ts+1 added-9 removed
20 unmodified lines21 22 /**23 Executes a command using `file ...arguments`.24 25-Arguments are automatically escaped. They can contain any character, including spaces, tabs and newlines.26-25 When `command` is a template string, it includes both the `file` and its `arguments`.26 29-The `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.28 31-When `command` is a template string, arguments can contain any character, but spaces, tabs and newlines must use `${}` like `` execa`echo ${'has space'}` ``.32-33-The `command` template string can use multiple lines and indentation.34-35-`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.36-29 @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 linesmodified:types/methods/main-sync.d.ts-11 removed
22 unmodified lines23 Same as `execa()` but synchronous.24 25 Returns or throws a subprocess `result`. The `subprocess` is not returned: its methods and properties are not available.26 27-The 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.37-27 @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` error55 unmodified linesmodified:types/methods/script.d.ts+1 added-1 removed
46 unmodified lines47 s: ExecaScriptSync<OptionsType>;48 } & ExecaScriptCommon<OptionsType>;49 50 /**51-Same as `execa()` but using the `stdin: 'inherit'` and `preferLocal: true` options.51+Same as `execa()` but using script-friendly default options.52 53 Just like `execa()`, this can use the template string syntax or bind options. It can also be run synchronously using `$.sync()` or `$.s()`.54 55 This is the preferred method when executing multiple commands in a script file.30 unmodified linesmodified:types/return/final-error.d.ts+2 added-12 removed
22 unmodified lines23 | 'originalMessage'24 | 'code';25 26 /**27-Exception 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 subprocesses27+Exception thrown when the subprocess fails.28 29 This has the same shape as successful results, with a few additional properties.30 */31 export class ExecaError<OptionsType extends Options = Options> extends CommonError<false, OptionsType> {32 readonly name: 'ExecaError';33 }34 35 /**41-Exception 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 subprocesses36+Exception thrown when the subprocess fails.37 38 This has the same shape as successful results, with a few additional properties.39 */40 export class ExecaSyncError<OptionsType extends SyncOptions = SyncOptions> extends CommonError<true, OptionsType> {2 unmodified linesmodified:types/return/result.d.ts+31 added-34 removed
8 unmodified lines9 IsSync extends boolean = boolean,10 OptionsType extends CommonOptions = CommonOptions,11 > {12 /**13- The file and arguments that were run, for logging purposes.14-15- 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;16 17 /**18 Same as `command` but escaped.21-22- Unlike `command`, control characters are escaped, which makes it safe to print in a terminal.23-24- 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;21 22 /**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.24 25 This is `undefined` when the subprocess could not be spawned or was terminated by a signal.26 */27 exitCode?: number;28 29 /**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)).31 39- 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`.33+34+ 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>;37 38 /**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)).40 46- 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`.42+43+ 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>;46 47 /**48+ The output of the subprocess with `result.stdout` and `result.stderr` interleaved.49+50+ This requires the `all` option to be `true`.51+52+ 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`.53+54+ 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>;57+58+ /**59 The output of the subprocess on `stdin`, `stdout`, `stderr` and other file descriptors.60 53- 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`.62+63+ Items are arrays when their corresponding `stdio` option is a transform in object mode.64 */65 stdio: ResultStdioArray<OptionsType>;66 67 /**1 unmodified line69 */70 failed: boolean;71 72 /**63- Whether the subprocess timed out.73+ Whether the subprocess timed out due to the `timeout` option.74 */75 timedOut: boolean;76 77 /**12 unmodified lines90 */91 signal?: string;92 93 /**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.95 96 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 lines117 */118 isMaxBuffer: boolean;119 120 /**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.122 113- 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`.116-117- 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>;120-121- /**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.123-123 This array is initially empty and is populated each time the `subprocess.pipe()` method resolves.124 */125 pipedFrom: Unless<IsSync, ExecaResult[], []>;126 127 /**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.130-131- 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;131 132 /**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;136 137 /**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.139 143- 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;143 144 /**43 unmodified linesmodified:types/subprocess/subprocess.d.ts+8 added-32 removed
39 unmodified lines40 */41 send: HasIpc<OptionsType> extends true ? ChildProcess['send'] : undefined;42 43 /**44- The subprocess `stdin` as a stream.44+ The subprocess [`stdin`](https://en.wikipedia.org/wiki/Standard_streams#Standard_input_(stdin)) as a stream.45 46 This is `null` if the `stdin` option is set to `'inherit'`, `'ignore'`, `Readable` or `integer`.47-48- 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>;49 50 /**53- The subprocess `stdout` as a stream.51+ The subprocess [`stdout`](https://en.wikipedia.org/wiki/Standard_streams#Standard_output_(stdout)) as a stream.52 55- This is `null` if the `stdout` option is set to `'inherit'`, `'ignore'`, `Writable` or `integer`.56-57- 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>;56 57 /**62- The subprocess `stderr` as a stream.58+ The subprocess [`stderr`](https://en.wikipedia.org/wiki/Standard_streams#Standard_error_(stderr)) as a stream.59 64- This is `null` if the `stderr` option is set to `'inherit'`, `'ignore'`, `Writable` or `integer`.65-66- 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>;63 64 /**65 Stream combining/interleaving `subprocess.stdout` and `subprocess.stderr`.66 73- 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`.68 77- 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>;72 73 /**74 The subprocess `stdin`, `stdout`, `stderr` and other files descriptors as an array of streams.75 84- Each array item is `null` if the corresponding `stdin`, `stdout`, `stderr` or `stdio` option is set to `'inherit'`, `'ignore'`, `Stream` or `integer`.85-86- 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>;79 80 /**9 unmodified lines90 kill(error?: Error): ReturnType<ChildProcess['kill']>;91 92 /**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.104-105- 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']>;96 97 /**2 unmodified lines100 iterable<IterableOptions extends ReadableOptions = {}>(readableOptions?: IterableOptions): SubprocessAsyncIterable<IterableOptions['binary'], OptionsType['encoding']>;101 102 /**103 Converts the subprocess to a readable stream.116-117- 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.118-119- Before using this method, please first consider the `stdin`/`stdout`/`stderr`/`stdio` options, `subprocess.pipe()` or `subprocess.iterable()`.104 */105 readable(readableOptions?: ReadableOptions): Readable;106 107 /**108 Converts the subprocess to a writable stream.125-126- 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.127-128- Before using this method, please first consider the `stdin`/`stdout`/`stderr`/`stdio` options or `subprocess.pipe()`.109 */110 writable(writableOptions?: WritableOptions): Writable;111 112 /**113 Converts the subprocess to a duplex stream.134-135- 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.136-137- 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 linesmodified:types/convert.d.ts+5 added-5 removed
3 unmodified lines4 5 // `subprocess.readable|duplex|iterable()` options6 export 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.9 10 `"all"` reads both `stdout` and `stderr`. This requires the `all` option to be `true`.11 12 @default 'stdout'13 */14 readonly from?: FromOption;15 16 /**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.18 19- 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()`).20 21 This is always `true` when the `encoding` option is binary.22 23 @default `false` with `subprocess.iterable()`, `true` otherwise24 */25 readonly binary?: boolean;26 27 /**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.29 30 @default `false` with `subprocess.iterable()`, `true` otherwise31 */32 readonly preserveNewlines?: boolean;1 unmodified line34 35 // `subprocess.writable|duplex()` options36 export 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.39 40 @default 'stdin'41 */42 readonly to?: ToOption;16 unmodified linesmodified:types/pipe.d.ts+2 added-10 removed
5 unmodified lines6 7 // `subprocess.pipe()` options8 type 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.11 12 `"all"` pipes both `stdout` and `stderr`. This requires the `all` option to be `true`.13 */14 readonly from?: FromOption;15 16 /**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;20 21 /**22 Unpipe the subprocess when the signal aborts.23-24- The `subprocess.pipe()` method will be rejected with a cancellation error.23 */24 readonly unpipeSignal?: AbortSignal;25 };26 2 unmodified lines29 /**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.31 32 This follows the same syntax as `execa(file, arguments?, options?)` except both regular options and pipe-specific options can be specified.35-36- This can be called multiple times to chain a series of subprocesses.37-38- 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 lines51 => Promise<ExecaResult<OptionsType>> & PipableSubprocess;52 53 /**54 Like `subprocess.pipe(file, arguments?, options?)` but using the return value of another `execa()` call instead.61-62- 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 lines46 ## Why47 48 This package improves [`child_process`](https://nodejs.org/api/child_process.html) methods with:49 50-- [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.65 66 ## Install67 68 ```sh69 npm install execa70 ```71 72+## Documentation73+74+Execution: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)83+84+Input/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)90+91+Advanced 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)98+99 ## Usage100 101 ### Promise interface102 50 unmodified lines153 ```154 155 ### Scripts156 130-For more information about Execa scripts, please see [this page](docs/scripts.md).131-157 #### Basic158 159 ```js160 import {$} from 'execa';150 unmodified lines311 _Returns_: [`Subprocess`](#subprocess)312 313 Executes a command using `file ...arguments`.314 290-Arguments are [automatically escaped](#shell-syntax). They can contain any character, including spaces, tabs and newlines.315+More info on the [syntax](docs/execution.md#array-syntax) and [escaping](docs/escaping.md#array-syntax).316 317 #### execa\`command\`318 #### execa(options)\`command\`319 320 `command`: `string`\321 `options`: [`Options`](#options)\322 _Returns_: [`Subprocess`](#subprocess)323 299-Executes a command. `command` is a [template string](#template-string-syntax) and includes both the `file` and its `arguments`.324+Executes a command. `command` is a [template string](docs/execution.md#template-string-syntax) that includes both the `file` and its `arguments`.325 301-The `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.326+More info on the [syntax](docs/execution.md#template-string-syntax) and [escaping](docs/escaping.md#template-string-syntax).327 303-Arguments are [automatically escaped](#shell-syntax). They can contain any character, but spaces, tabs and newlines must use `${}` like `` execa`echo ${'has space'}` ``.304-305-The `command` template string can use [multiple lines and indentation](docs/scripts.md#multiline-commands).306-328 #### execa(options)329 330 `options`: [`Options`](#options)\331 _Returns_: [`execa`](#execafile-arguments-options)332 333 Returns a new instance of Execa but with different default [`options`](#options). Consecutive calls are merged to previous ones.334 314-This allows setting global options or [sharing options](#globalshared-options) between multiple commands.335+[More info.](docs/execution.md#globalshared-options)336 337 #### execaSync(file, arguments?, options?)338 #### execaSync\`command\`339 340 Same as [`execa()`](#execafile-arguments-options) but synchronous.341 342 Returns or throws a subprocess [`result`](#result). The [`subprocess`](#subprocess) is not returned: its methods and properties are not available.343 323-The 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)345 346 #### $(file, arguments?, options?)347 348 `file`: `string | URL`\349 `arguments`: `string[]`\350 `options`: [`Options`](#options)\351 _Returns_: [`Subprocess`](#subprocess)352 341-Same as [`execa()`](#execafile-arguments-options) but using the [`stdin: 'inherit'`](#optionsstdin) and [`preferLocal: true`](#optionspreferlocal) options.353+Same as [`execa()`](#execafile-arguments-options) but using [script-friendly default options](docs/scripts.md#script-files).354 343-Just 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()`.355+Just 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()`.356 345-This is the preferred method when executing multiple commands in a script file. For more information, please see [this page](docs/scripts.md).357+This is the preferred method when executing multiple commands in a script file.358 359+[More info.](docs/scripts.md)360+361 #### execaNode(scriptPath, arguments?, options?)362 363 `scriptPath`: `string | URL`\364 `arguments`: `string[]`\2 unmodified lines367 368 Same as [`execa()`](#execafile-arguments-options) but using the [`node: true`](#optionsnode) option.369 Executes a Node.js file using `node scriptPath ...arguments`.370 357-Just like `execa()`, this can use the [template string syntax](#execacommand) or [bind options](#execaoptions).371+Just like `execa()`, this can use the [template string syntax](docs/execution.md#template-string-syntax) or [bind options](docs/execution.md#globalshared-options).372 373 This is the preferred method when executing Node.js files.374 375+[More info.](docs/node.md)376+377 #### execaCommand(command, options?)378 379 `command`: `string`\380 `options`: [`Options`](#options)\381 _Returns_: [`Subprocess`](#subprocess)382 367-[`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.383+Executes a command. `command` is a string that includes both the `file` and its `arguments`.384 369-This is only intended for very specific cases, such as a REPL. This should be avoided otherwise.385+This 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.386 371-Just like `execa()`, this can [bind options](#execaoptions). It can also be [run synchronously](#execasyncfile-arguments-options) using `execaCommandSync()`.387+Just like `execa()`, this can [bind options](docs/execution.md#globalshared-options). It can also be [run synchronously](#execasyncfile-arguments-options) using `execaCommandSync()`.388 373-Arguments 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)390 375-### Shell syntax376-377-For 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.378-391 ### subprocess392 393 The 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.396 397+[More info.](docs/execution.md#subprocess)398+399 #### subprocess.pipe(file, arguments?, options?)400 401 `file`: `string | URL`\402 `arguments`: `string[]`\403 `options`: [`Options`](#options) and [`PipeOptions`](#pipeoptions)\404 _Returns_: [`Promise<Result>`](#result)405 392-[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.407 408 This 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.409 396-This can be called multiple times to chain a series of subprocesses.410+[More info.](docs/pipe.md#array-syntax)411 398-Multiple subprocesses can be piped to the same subprocess. Conversely, the same subprocess can be piped to multiple other subprocesses.399-412 #### subprocess.pipe\`command\`413 #### subprocess.pipe(options)\`command\`414 415 `command`: `string`\416 `options`: [`Options`](#options) and [`PipeOptions`](#pipeoptions)\417 _Returns_: [`Promise<Result>`](#result)418 407-Like [`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).419+Like [`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).420 421+[More info.](docs/pipe.md#template-string-syntax)422+423 #### subprocess.pipe(secondSubprocess, pipeOptions?)424 425 `secondSubprocess`: [`execa()` return value](#subprocess)\426 `pipeOptions`: [`PipeOptions`](#pipeoptions)\427 _Returns_: [`Promise<Result>`](#result)428 415-Like [`subprocess.pipe(file, arguments?, options?)`](#subprocesspipefile-arguments-options) but using the [return value](#subprocess) of another `execa()` call instead.429+Like [`subprocess.pipe(file, arguments?, options?)`](#subprocesspipefile-arguments-options) but using the [return value](#subprocess) of another [`execa()`](#execafile-arguments-options) call instead.430 417-This 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)432 433 ##### pipeOptions434 435 Type: `object`2 unmodified lines438 439 Type: `"stdout" | "stderr" | "all" | "fd3" | "fd4" | ...`\440 Default: `"stdout"`441 428-Which stream to pipe from the source subprocess. A file descriptor like `"fd3"` can also be passed.442+Which stream to pipe from the source subprocess. A [file descriptor](https://en.wikipedia.org/wiki/File_descriptor) like `"fd3"` can also be passed.443 430-`"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`.445 446+[More info.](docs/pipe.md#source-file-descriptor)447+448 ##### pipeOptions.to449 450 Type: `"stdin" | "fd3" | "fd4" | ...`\451 Default: `"stdin"`452 437-Which stream to pipe to the destination subprocess. A file descriptor like `"fd3"` can also be passed.453+Which [stream](#subprocessstdin) to pipe to the destination subprocess. A [file descriptor](https://en.wikipedia.org/wiki/File_descriptor) like `"fd3"` can also be passed.454 455+[More info.](docs/pipe.md#destination-file-descriptor)456+457 ##### pipeOptions.unpipeSignal458 459 Type: [`AbortSignal`](https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal)460 461 Unpipe the subprocess when the signal aborts.462 445-The [`subprocess.pipe()`](#subprocesspipefile-arguments-options) method will be rejected with a cancellation error.463+[More info.](docs/pipe.md#unpipe)464 465 #### subprocess.kill(signal, error?)466 #### subprocess.kill(error?)467 6 unmodified lines474 This returns `false` when the signal could not be sent, for example when the subprocess has already exited.475 476 When 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).477 460-[More info.](https://nodejs.org/api/child_process.html#subprocesskillsignal)478+[More info.](docs/termination.md)479 480 #### subprocess.pid481 482 _Type_: `number | undefined`1 unmodified line484 Process identifier ([PID](https://en.wikipedia.org/wiki/Process_identifier)).485 486 This is `undefined` if the subprocess failed to spawn.487 488+[More info.](docs/termination.md#inter-process-termination)489+490 #### subprocess.send(message)491 492 `message`: `unknown`\493 _Returns_: `boolean`4 unmodified lines498 This returns `true` on success.499 500 This requires the [`ipc`](#optionsipc) option to be `true`.501 482-[More info.](https://nodejs.org/api/child_process.html#subprocesssendmessage-sendhandle-options-callback)502+[More info.](docs/ipc.md#exchanging-messages)503 504 #### subprocess.on('message', (message) => void)505 506 `message`: `unknown`2 unmodified lines509 The subprocess sends it using [`process.send(message)`](https://nodejs.org/api/process.html#processsendmessage-sendhandle-options-callback).510 511 This requires the [`ipc`](#optionsipc) option to be `true`.512 493-[More info.](https://nodejs.org/api/child_process.html#event-message)513+[More info.](docs/ipc.md#exchanging-messages)514 515 #### subprocess.stdin516 517 Type: [`Writable | null`](https://nodejs.org/api/stream.html#class-streamwritable)518 499-The subprocess [`stdin`](#optionsstdin) as a stream.519+The subprocess [`stdin`](https://en.wikipedia.org/wiki/Standard_streams#Standard_input_(stdin)) as a stream.520 501-This is `null` if the [`stdin`](#optionsstdin) option is set to `'inherit'`, `'ignore'`, `Readable` or `integer`.521+This 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).522 503-This 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)524 525 #### subprocess.stdout526 527 Type: [`Readable | null`](https://nodejs.org/api/stream.html#class-streamreadable)528 509-The subprocess [`stdout`](#optionsstdout) as a stream.529+The subprocess [`stdout`](https://en.wikipedia.org/wiki/Standard_streams#Standard_output_(stdout)) as a stream.530 511-This is `null` if the [`stdout`](#optionsstdout) option is set to `'inherit'`, `'ignore'`, `Writable` or `integer`.531+This 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`.532 513-This 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)534 535 #### subprocess.stderr536 537 Type: [`Readable | null`](https://nodejs.org/api/stream.html#class-streamreadable)538 519-The subprocess [`stderr`](#optionsstderr) as a stream.539+The subprocess [`stderr`](https://en.wikipedia.org/wiki/Standard_streams#Standard_error_(stderr)) as a stream.540 521-This is `null` if the [`stderr`](#optionsstdout) option is set to `'inherit'`, `'ignore'`, `Writable` or `integer`.541+This 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`.542 523-This 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)544 545 #### subprocess.all546 547 Type: [`Readable | undefined`](https://nodejs.org/api/stream.html#class-streamreadable)548 529-Stream [combining/interleaving](#ensuring-all-output-is-interleaved) [`subprocess.stdout`](#subprocessstdout) and [`subprocess.stderr`](#subprocessstderr).549+Stream combining/interleaving [`subprocess.stdout`](#subprocessstdout) and [`subprocess.stderr`](#subprocessstderr).550 531-This 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`.551+This requires the [`all`](#optionsall) option to be `true`.552 535-This 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.553+This 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`.554 555+More info on [interleaving](docs/output.md#interleaved-output) and [streaming](docs/streams.md#manual-streaming).556+557 #### subprocess.stdio558 559 Type: [`[Writable | null, Readable | null, Readable | null, ...Array<Writable | Readable | null>]`](https://nodejs.org/api/stream.html#class-streamreadable)560 541-The subprocess `stdin`, `stdout`, `stderr` and [other files descriptors](#optionsstdio) as an array of streams.561+The subprocess [`stdin`](#subprocessstdin), [`stdout`](#subprocessstdout), [`stderr`](#subprocessstderr) and [other files descriptors](#optionsstdio) as an array of streams.562 543-Each 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`.563+Each 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`.564 545-This 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)566 567 #### subprocess\[Symbol.asyncIterator\]()568 549-_Returns_: `AsyncIterable`569+_Returns_: [`AsyncIterable`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#the_async_iterator_and_async_iterable_protocols)570 571 Subprocesses are [async iterables](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol/asyncIterator). They iterate over each output line.572 553-The 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)574 575 #### subprocess.iterable(readableOptions?)576 577 `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)579 580 Same as [`subprocess[Symbol.asyncIterator]`](#subprocesssymbolasynciterator) except [options](#readableoptions) can be provided.581 582+[More info.](docs/lines.md#progressive-splitting)583+584 #### subprocess.readable(readableOptions?)585 586 `readableOptions`: [`ReadableOptions`](#readableoptions)\587 _Returns_: [`Readable`](https://nodejs.org/api/stream.html#class-streamreadable) Node.js stream588 589 Converts the subprocess to a readable stream.590 569-Unlike [`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)592 571-Before 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).572-593 #### subprocess.writable(writableOptions?)594 595 `writableOptions`: [`WritableOptions`](#writableoptions)\596 _Returns_: [`Writable`](https://nodejs.org/api/stream.html#class-streamwritable) Node.js stream597 598 Converts the subprocess to a writable stream.599 580-Unlike [`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)601 582-Before using this method, please first consider the [`stdin`](#optionsstdin)/[`stdout`](#optionsstdout)/[`stderr`](#optionsstderr)/[`stdio`](#optionsstdio) options or [`subprocess.pipe()`](#subprocesspipefile-arguments-options).583-602 #### subprocess.duplex(duplexOptions?)603 604 `duplexOptions`: [`ReadableOptions | WritableOptions`](#readableoptions)\605 _Returns_: [`Duplex`](https://nodejs.org/api/stream.html#class-streamduplex) Node.js stream606 607 Converts the subprocess to a duplex stream.608 591-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.609+[More info.](docs/streams.md#converting-a-subprocess-to-a-stream)610 593-Before 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).594-611 ##### readableOptions612 613 Type: `object`614 1 unmodified line616 617 Type: `"stdout" | "stderr" | "all" | "fd3" | "fd4" | ...`\618 Default: `"stdout"`619 604-Which stream to read from the subprocess. A file descriptor like `"fd3"` can also be passed.620+Which stream to read from the subprocess. A [file descriptor](https://en.wikipedia.org/wiki/File_descriptor) like `"fd3"` can also be passed.621 606-`"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`.623 624+[More info.](docs/streams.md#different-file-descriptor)625+626 ##### readableOptions.binary627 628 Type: `boolean`\629 Default: `false` with [`subprocess.iterable()`](#subprocessiterablereadableoptions), `true` with [`subprocess.readable()`](#subprocessreadablereadableoptions)/[`subprocess.duplex()`](#subprocessduplexduplexoptions)630 613-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).631+If `false`, iterates over lines. Each line is a string.632 615-If `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).633+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()`](#subprocessiterablereadableoptions)) or a [`Buffer`](https://nodejs.org/api/buffer.html#class-buffer) (with [`subprocess.readable()`](#subprocessreadablereadableoptions)/[`subprocess.duplex()`](#subprocessduplexduplexoptions)).634 635 This is always `true` when the [`encoding`](#optionsencoding) option is binary.636 637+More info for [iterables](docs/binary.md#iterable) and [streams](docs/binary.md#streams).638+639 ##### readableOptions.preserveNewlines640 641 Type: `boolean`\642 Default: `false` with [`subprocess.iterable()`](#subprocessiterablereadableoptions), `true` with [`subprocess.readable()`](#subprocessreadablereadableoptions)/[`subprocess.duplex()`](#subprocessduplexduplexoptions)643 624-If both this option and the [`binary`](#readableoptionsbinary) option is `false`, newlines are stripped from each line.644+If both this option and the [`binary`](#readableoptionsbinary) option is `false`, [newlines](https://en.wikipedia.org/wiki/Newline) are stripped from each line.645 646+[More info.](docs/lines.md#iterable)647+648 ##### writableOptions649 650 Type: `object`651 1 unmodified line653 654 Type: `"stdin" | "fd3" | "fd4" | ...`\655 Default: `"stdin"`656 635-Which stream to write to the subprocess. A file descriptor like `"fd3"` can also be passed.657+Which [stream](#subprocessstdin) to write to the subprocess. A [file descriptor](https://en.wikipedia.org/wiki/File_descriptor) like `"fd3"` can also be passed.658 659+[More info.](docs/streams.md#different-file-descriptor)660+661 ### Result662 663 Type: `object`664 641-Result of a subprocess execution.665+[Result](docs/execution.md#result) of a subprocess execution.666 643-When the subprocess [fails](#resultfailed), it is rejected with an [`ExecaError`](#execaerror) instead.667+When the subprocess [fails](docs/errors.md#subprocess-failure), it is rejected with an [`ExecaError`](#execaerror) instead.668 669 #### result.command670 671 Type: `string`672 649-The file and arguments that were run, for logging purposes.673+The file and [arguments](docs/input.md#command-arguments) that were run.674 651-This 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)676 677 #### result.escapedCommand678 679 Type: `string`680 681 Same as [`command`](#resultcommand) but escaped.682 659-Unlike `command`, control characters are escaped, which makes it safe to print in a terminal.683+[More info.](docs/debugging.md#command)684 661-This can also be copied and pasted into a shell, for debugging purposes.662-Since the escaping is fairly basic, this should not be executed directly as a subprocess, including using [`execa()`](#execafile-arguments-options) or [`execaCommand()`](#execacommandcommand-options).663-685 #### result.cwd686 687 Type: `string`688 689 The [current directory](#optionscwd) in which the command was run.690 691+[More info.](docs/environment.md#current-directory)692+693 #### result.durationMs694 695 Type: `number`696 697 Duration of the subprocess, in milliseconds.698 699+[More info.](docs/debugging.md#duration)700+701 #### result.stdout702 703 Type: `string | Uint8Array | string[] | Uint8Array[] | unknown[] | undefined`704 680-The output of the subprocess on `stdout`.705+The output of the subprocess on [`stdout`](https://en.wikipedia.org/wiki/Standard_streams#Standard_output_(stdout)).706 682-This 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).707+This 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`.708 709+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).710+711+[More info.](docs/output.md#stdout-and-stderr)712+713 #### result.stderr714 715 Type: `string | Uint8Array | string[] | Uint8Array[] | unknown[] | undefined`716 688-The output of the subprocess on `stderr`.717+The output of the subprocess on [`stderr`](https://en.wikipedia.org/wiki/Standard_streams#Standard_error_(stderr)).718 690-This 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).719+This 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`.720 721+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).722+723+[More info.](docs/output.md#stdout-and-stderr)724+725 #### result.all726 727 Type: `string | Uint8Array | string[] | Uint8Array[] | unknown[] | undefined`728 696-The output of the subprocess with [`result.stdout`](#resultstdout) and [`result.stderr`](#resultstderr) [interleaved](#ensuring-all-output-is-interleaved).729+The output of the subprocess with [`result.stdout`](#resultstdout) and [`result.stderr`](#resultstderr) interleaved.730 698-This 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`.731+This requires the [`all`](#optionsall) option to be `true`.732 733+This 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`.734+735 This 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).736 737+[More info.](docs/output.md#interleaved-output)738+739 #### result.stdio740 741 Type: `Array<string | Uint8Array | string[] | Uint8Array[] | unknown[] | undefined>`742 743 The output of the subprocess on [`stdin`](#optionsstdin), [`stdout`](#optionsstdout), [`stderr`](#optionsstderr) and [other file descriptors](#optionsstdio).744 710-Items 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).745+Items 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`.746 747+Items are arrays when their corresponding `stdio` option is a [transform in object mode](docs/transform.md#object-mode).748+749+[More info.](docs/output.md#additional-file-descriptors)750+751 #### result.failed752 753 Type: `boolean`754 755 Whether the subprocess failed to run.756 757+[More info.](docs/errors.md#subprocess-failure)758+759 #### result.timedOut760 761 Type: `boolean`762 722-Whether the subprocess timed out.763+Whether the subprocess timed out due to the [`timeout`](#optionstimeout) option.764 765+[More info.](docs/termination.md#timeout)766+767 #### result.isCanceled768 769 Type: `boolean`770 771 Whether the subprocess was canceled using the [`cancelSignal`](#optionscancelsignal) option.772 773+[More info.](docs/termination.md#canceling)774+775 #### result.isTerminated776 777 Type: `boolean`778 734-Whether the subprocess was terminated by a signal (like `SIGTERM`) sent by either:779+Whether 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).782 783+[More info.](docs/termination.md#signal-name-and-description)784+785 #### result.isMaxBuffer786 787 Type: `boolean`788 789 Whether the subprocess failed because its output was larger than the [`maxBuffer`](#optionsmaxbuffer) option.790 791+[More info.](docs/output.md#big-output)792+793 #### result.exitCode794 795 Type: `number | undefined`796 748-The numeric exit code of the subprocess that was run.797+The numeric [exit code](https://en.wikipedia.org/wiki/Exit_status) of the subprocess that was run.798 799 This is `undefined` when the subprocess could not be spawned or was terminated by a [signal](#resultsignal).800 801+[More info.](docs/errors.md#exit-code)802+803 #### result.signal804 805 Type: `string | undefined`806 756-The name of the signal (like `SIGTERM`) that terminated the subprocess, sent by either:807+The 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).810 760-If a signal terminated the subprocess, this property is defined and included in the error message. Otherwise it is `undefined`.811+If a signal terminated the subprocess, this property is defined and included in the [error message](#errormessage). Otherwise it is `undefined`.812 813+[More info.](docs/termination.md#signal-name-and-description)814+815 #### result.signalDescription816 817 Type: `string | undefined`818 766-A human-friendly description of the signal that was used to terminate the subprocess. For example, `Floating point arithmetic error`.819+A human-friendly description of the [signal](docs/termination.md#signal-termination) that was used to terminate the subprocess.820 821 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.822 823+[More info.](docs/termination.md#signal-name-and-description)824+825 #### result.pipedFrom826 827 Type: [`Array<Result | ExecaError>`](#result)828 774-Results 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.830 831 This array is initially empty and is populated each time the [`subprocess.pipe()`](#subprocesspipefile-arguments-options) method resolves.832 833+[More info.](docs/pipe.md#errors)834+835 ### ExecaError836 ### ExecaSyncError837 838 Type: `Error`839 783-Exception 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 subprocesses840+Exception thrown when the subprocess [fails](docs/errors.md#subprocess-failure).841 842 This has the same shape as [successful results](#result), with the following additional properties.843 844+[More info.](docs/errors.md)845+846 #### error.message847 848 Type: `string`849 796-Error 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.850+Error message when the subprocess [failed](docs/errors.md#subprocess-failure) to run.851 798-The 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)853 854 #### error.shortMessage855 856 Type: `string`857 804-This is the same as the [`message` property](#errormessage) except it does not include the subprocess [`stdout`](#resultstdout)/[`stderr`](#resultstderr)/[`stdio`](#resultstdio).858+This is the same as [`error.message`](#errormessage) except it does not include the subprocess [output](docs/output.md).859 860+[More info.](docs/errors.md#error-message)861+862 #### error.originalMessage863 864 Type: `string | undefined`865 810-Original 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.866+Original error message. This is the same as [`error.message`](#errormessage) excluding the subprocess [output](docs/output.md) and some additional information added by Execa.867 812-This exists only if the subprocess exited due to an `error` event or a timeout.868+[More info.](docs/errors.md#error-message)869 870 #### error.cause871 872 Type: `unknown | undefined`1 unmodified line874 Underlying error, if there is one. For example, this is set by [`subprocess.kill(error)`](#subprocesskillerror).875 876 This is usually an `Error` instance.877 878+[More info.](docs/termination.md#error-message-and-stack-trace)879+880 #### error.code881 882 Type: `string | undefined`883 4 unmodified lines888 Type: `object`889 890 This lists all options for [`execa()`](#execafile-arguments-options) and the [other methods](#methods).891 834-Some 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.892+The 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).893 836-```js837-await execa('./run.js', {verbose: 'full'}) // Same value for stdout and stderr838-await execa('./run.js', {verbose: {stdout: 'none', stderr: 'full'}}) // Different values839-```840-894 #### options.reject895 896 Type: `boolean`\897 Default: `true`898 846-Setting this to `false` resolves the promise with the [error](#execaerror) instead of rejecting it.899+Setting this to `false` resolves the [result's promise](#subprocess) with the [error](#execaerror) instead of rejecting it.900 901+[More info.](docs/errors.md#preventing-exceptions)902+903 #### options.shell904 905 Type: `boolean | string | URL`\906 Default: `false`907 853-If `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.908+If `true`, runs the command inside of a [shell](https://en.wikipedia.org/wiki/Shell_(computing)).909 855-We 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.910+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.911 912+We [recommend against](docs/shell.md#avoiding-shells) using this option.913+914+[More info.](docs/shell.md)915+916 #### options.cwd917 918 Type: `string | URL`\919 Default: `process.cwd()`920 865-Current working directory of the subprocess.921+Current [working directory](https://en.wikipedia.org/wiki/Working_directory) of the subprocess.922 923 This is also used to resolve the [`nodePath`](#optionsnodepath) option when it is a relative path.924 925+[More info.](docs/environment.md#current-directory)926+927 #### options.env928 929 Type: `object`\872-Default: `process.env`930+Default: [`process.env`](https://nodejs.org/api/process.html#processenv)931 874-Environment key-value pairs.932+[Environment variables](https://en.wikipedia.org/wiki/Environment_variable).933 934 Unless the [`extendEnv`](#optionsextendenv) option is `false`, the subprocess also uses the current process' environment variables ([`process.env`](https://nodejs.org/api/process.html#processenv)).935 936+[More info.](docs/input.md#environment-variables)937+938 #### options.extendEnv939 940 Type: `boolean`\941 Default: `true`942 943 If `true`, the subprocess uses both the [`env`](#optionsenv) option and the current process' environment variables ([`process.env`](https://nodejs.org/api/process.html#processenv)).944 If `false`, only the `env` option is used, not `process.env`.945 946+[More info.](docs/input.md#environment-variables)947+948 #### options.preferLocal949 950 Type: `boolean`\951 Default: `true` with [`$`](#file-arguments-options), `false` otherwise952 891-Prefer locally installed binaries when looking for a binary to execute.\892-If you `$ npm install foo`, you can then `execa('foo')`.953+Prefer locally installed binaries when looking for a binary to execute.954 955+[More info.](docs/environment.md#local-binaries)956+957 #### options.localDir958 959 Type: `string | URL`\897-Default: `process.cwd()`960+Default: [`cwd`](#optionscwd) option961 899-Preferred path to find locally installed binaries in (use with `preferLocal`).962+Preferred path to find locally installed binaries, when using the [`preferLocal`](#optionspreferlocal) option.963 964+[More info.](docs/environment.md#local-binaries)965+966 #### options.node967 968 Type: `boolean`\969 Default: `true` with [`execaNode()`](#execanodescriptpath-arguments-options), `false` otherwise970 971 If `true`, runs with Node.js. The first argument must be a Node.js file.972 973+[More info.](docs/node.md)974+975 #### options.nodeOptions976 977 Type: `string[]`\978 Default: [`process.execArgv`](https://nodejs.org/api/process.html#process_process_execargv) (current Node.js CLI options)979 913-List of [CLI options](https://nodejs.org/api/cli.html#cli_options) passed to the [Node.js executable](#optionsnodepath).980+List of [CLI flags](https://nodejs.org/api/cli.html#cli_options) passed to the [Node.js executable](#optionsnodepath).981 982 Requires the [`node`](#optionsnode) option to be `true`.983 984+[More info.](docs/node.md#nodejs-cli-flags)985+986 #### options.nodePath987 988 Type: `string | URL`\989 Default: [`process.execPath`](https://nodejs.org/api/process.html#process_process_execpath) (current Node.js executable)990 991 Path to the Node.js executable.992 924-For example, this can be used together with [`get-node`](https://github.com/ehmicky/get-node) to run a specific Node.js version.925-993 Requires the [`node`](#optionsnode) option to be `true`.994 995+[More info.](docs/node.md#nodejs-version)996+997 #### options.verbose998 999 Type: `'none' | 'short' | 'full'`\1000 Default: `'none'`1001 933-If `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.1002+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.1003 935-If `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.1004+If `verbose` is `'full'`, the command's [`stdout`](https://en.wikipedia.org/wiki/Standard_streams#Standard_output_(stdout)) and `stderr` are also printed.1005 940-This can also be set to `'full'` by setting the `NODE_DEBUG=execa` environment variable in the current process.1006+By default, this applies to both `stdout` and `stderr`, but [different values can also be passed](docs/output.md#stdoutstderr-specific-options).1007 942-By default, this applies to both `stdout` and `stderr`, but [different values can also be passed](#options).1008+[More info.](docs/debugging.md#verbose-mode)1009 1010 #### options.buffer1011 1012 Type: `boolean`\1013 Default: `true`1014 949-Whether to return the subprocess' output using the [`result.stdout`](#resultstdout), [`result.stderr`](#resultstderr), [`result.all`](#resultall) and [`result.stdio`](#resultstdio) properties.1015+When `buffer` is `false`, the [`result.stdout`](#resultstdout), [`result.stderr`](#resultstderr), [`result.all`](#resultall) and [`result.stdio`](#resultstdio) properties are not set.1016 951-On failure, the [`error.stdout`](#resultstdout), [`error.stderr`](#resultstderr), [`error.all`](#resultall) and [`error.stdio`](#resultstdio) properties are used instead.1017+By default, this applies to both `stdout` and `stderr`, but [different values can also be passed](docs/output.md#stdoutstderr-specific-options).1018 953-When `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)1020 955-By default, this applies to both `stdout` and `stderr`, but [different values can also be passed](#options).956-1021 #### options.input1022 1023 Type: `string | Uint8Array | stream.Readable`1024 961-Write some input to the subprocess' `stdin`.1025+Write some input to the subprocess' [`stdin`](https://en.wikipedia.org/wiki/Standard_streams#Standard_input_(stdin)).1026 1027 See also the [`inputFile`](#optionsinputfile) and [`stdin`](#optionsstdin) options.1028 1029+[More info.](docs/input.md#string-input)1030+1031 #### options.inputFile1032 1033 Type: `string | URL`1034 969-Use a file as input to the subprocess' `stdin`.1035+Use a file as input to the subprocess' [`stdin`](https://en.wikipedia.org/wiki/Standard_streams#Standard_input_(stdin)).1036 1037 See also the [`input`](#optionsinput) and [`stdin`](#optionsstdin) options.1038 1039+[More info.](docs/input.md#file-input)1040+1041 #### options.stdin1042 1043 Type: `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)\976-Default: `inherit` with [`$`](#file-arguments-options), `pipe` otherwise1044+Default: `'inherit'` with [`$`](#file-arguments-options), `'pipe'` otherwise1045 978-How 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`.1046+How 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).1047 991-This can be an [array of values](#redirect-stdinstdoutstderr-to-multiple-destinations) such as `['inherit', 'pipe']` or `[filePath, 'pipe']`.1048+This can be an [array of values](docs/output.md#multiple-targets) such as `['inherit', 'pipe']` or `[fileUrl, 'pipe']`.1049 993-This 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)1050+More info on [available values](docs/input.md), [streaming](docs/streams.md) and [transforms](docs/transform.md).1051 995-[More info.](https://nodejs.org/api/child_process.html#child_process_options_stdio)996-1052 #### options.stdout1053 1054 Type: `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)\1055 Default: `pipe`1056 1002-How 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).1057+How 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).1058 1013-This can be an [array of values](#redirect-stdinstdoutstderr-to-multiple-destinations) such as `['inherit', 'pipe']` or `[filePath, 'pipe']`.1059+This can be an [array of values](docs/output.md#multiple-targets) such as `['inherit', 'pipe']` or `[fileUrl, 'pipe']`.1060 1015-This 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)1061+More info on [available values](docs/output.md), [streaming](docs/streams.md) and [transforms](docs/transform.md).1062 1017-[More info.](https://nodejs.org/api/child_process.html#child_process_options_stdio)1018-1063 #### options.stderr1064 1065 Type: `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)\1066 Default: `pipe`1067 1024-How 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).1068+How 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).1069 1035-This can be an [array of values](#redirect-stdinstdoutstderr-to-multiple-destinations) such as `['inherit', 'pipe']` or `[filePath, 'pipe']`.1070+This can be an [array of values](docs/output.md#multiple-targets) such as `['inherit', 'pipe']` or `[fileUrl, 'pipe']`.1071 1037-This 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)1072+More info on [available values](docs/output.md), [streaming](docs/streams.md) and [transforms](docs/transform.md).1073 1039-[More info.](https://nodejs.org/api/child_process.html#child_process_options_stdio)1040-1074 #### options.stdio1075 1076 Type: `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)\1077 Default: `pipe`1078 1046-Like 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'}`.1079+Like 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'}`.1080 1048-A single string can be used as a shortcut. For example, `{stdio: 'pipe'}` is the same as `{stdin: 'pipe', stdout: 'pipe', stderr: 'pipe'}`.1081+A single string can be used [as a shortcut](docs/output.md#shortcut).1082 1050-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.1083+The 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).1084 1052-[More info.](https://nodejs.org/api/child_process.html#child_process_options_stdio)1085+More info on [available values](docs/output.md), [streaming](docs/streams.md) and [transforms](docs/transform.md).1086 1087 #### options.all1088 1089 Type: `boolean`\1090 Default: `false`1091 1059-Add 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`.1092+Add a [`subprocess.all`](#subprocessall) stream and a [`result.all`](#resultall) property.1093 1094+[More info.](docs/output.md#interleaved-output)1095+1096 #### options.lines1097 1098 Type: `boolean`\1099 Default: `false`1100 1101 Set [`result.stdout`](#resultstdout), [`result.stderr`](#resultstdout), [`result.all`](#resultall) and [`result.stdio`](#resultstdio) as arrays of strings, splitting the subprocess' output into lines.1102 1068-This cannot be used if the [`encoding`](#optionsencoding) option is binary.1103+This cannot be used if the [`encoding`](#optionsencoding) option is [binary](docs/binary.md#binary-output).1104 1070-By default, this applies to both `stdout` and `stderr`, but [different values can also be passed](#options).1105+By default, this applies to both `stdout` and `stderr`, but [different values can also be passed](docs/output.md#stdoutstderr-specific-options).1106 1107+[More info.](docs/lines.md#simple-splitting)1108+1109 #### options.encoding1110 1074-Type: `string`\1111+Type: `'utf8' | 'utf16le' | 'buffer' | 'hex' | 'base64' | 'base64url' | 'latin1' | 'ascii'`\1112 Default: `'utf8'`1113 1077-If the subprocess outputs text, specifies its character encoding, either `'utf8'` or `'utf16le'`.1114+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).1115 1116 If 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.1119 1120 The output is available with [`result.stdout`](#resultstdout), [`result.stderr`](#resultstderr) and [`result.stdio`](#resultstdio).1121 1122+[More info.](docs/binary.md)1123+1124 #### options.stripFinalNewline1125 1126 Type: `boolean`\1127 Default: `true`1 unmodified line1129 Strip the final [newline character](https://en.wikipedia.org/wiki/Newline) from the output.1130 1131 If the [`lines`](#optionslines) option is true, this applies to each output line instead.1132 1094-By default, this applies to both `stdout` and `stderr`, but [different values can also be passed](#options).1133+By default, this applies to both `stdout` and `stderr`, but [different values can also be passed](docs/output.md#stdoutstderr-specific-options).1134 1135+[More info.](docs/lines.md#newlines)1136+1137 #### options.maxBuffer1138 1139 Type: `number`\1140 Default: `100_000_000`1141 1142 Largest amount of data allowed on [`stdout`](#resultstdout), [`stderr`](#resultstderr) and [`stdio`](#resultstdio).1143 1103-When this threshold is hit, the subprocess fails and [`error.isMaxBuffer`](#resultismaxbuffer) becomes `true`.1144+By default, this applies to both `stdout` and `stderr`, but [different values can also be passed](docs/output.md#stdoutstderr-specific-options).1145 1105-This 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)1147 1111-By default, this applies to both `stdout` and `stderr`, but [different values can also be passed](#options).1112-1148 #### options.ipc1149 1150 Type: `boolean`\1151 Default: `true` if the [`node`](#optionsnode) option is enabled, `false` otherwise1152 1153 Enables exchanging messages with the subprocess using [`subprocess.send(message)`](#subprocesssendmessage) and [`subprocess.on('message', (message) => {})`](#subprocessonmessage-message--void).1154 1155+[More info.](docs/ipc.md)1156+1157 #### options.serialization1158 1122-Type: `string`\1159+Type: `'json' | 'advanced'`\1160 Default: `'advanced'`1161 1125-Specify 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)1162+Specify the kind of serialization used for sending messages between subprocesses when using the [`ipc`](#optionsipc) option.1163 1129-[More info.](https://nodejs.org/api/child_process.html#child_process_advanced_serialization)1164+[More info.](docs/ipc.md#message-type)1165 1166 #### options.detached1167 1168 Type: `boolean`\1169 Default: `false`1170 1136-Prepare subprocess to run independently of the current process. Specific behavior depends on the platform.1171+Run the subprocess independently from the current process.1172 1138-[More info.](https://nodejs.org/api/child_process.html#child_process_options_detached).1173+[More info.](docs/environment.md#background-subprocess)1174 1175 #### options.cleanup1176 1177 Type: `boolean`\1178 Default: `true`1179 1145-Kill 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.1180+Kill the subprocess when the current process exits.1181 1182+[More info.](docs/termination.md#current-process-exit)1183+1184 #### options.timeout1185 1186 Type: `number`\1187 Default: `0`1188 1189 If `timeout` is greater than `0`, the subprocess will be [terminated](#optionskillsignal) if it runs for longer than that amount of milliseconds.1190 1191+On timeout, [`result.timedOut`](#resulttimedout) becomes `true`.1192+1193+[More info.](docs/termination.md#timeout)1194+1195 #### options.cancelSignal1196 1197 Type: [`AbortSignal`](https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal)1198 1199 You can abort the subprocess using [`AbortController`](https://developer.mozilla.org/en-US/docs/Web/API/AbortController).1200 1201 When `AbortController.abort()` is called, [`result.isCanceled`](#resultiscanceled) becomes `true`.1202 1203+[More info.](docs/termination.md#canceling)1204+1205 #### options.forceKillAfterDelay1206 1207 Type: `number | false`\1208 Default: `5000`1209 1210 If the subprocess is terminated but does not exit, forcefully exit it by sending [`SIGKILL`](https://en.wikipedia.org/wiki/Signal_(IPC)#SIGKILL).1211 1171-The grace period is 5 seconds by default. This feature can be disabled with `false`.1212+[More info.](docs/termination.md#forceful-termination)1213 1173-This 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 arguments1176-1177-This 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 process1181-1182-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.1183-1214 #### options.killSignal1215 1216 Type: `string | number`\1187-Default: `SIGTERM`1217+Default: `'SIGTERM'`1218 1189-Signal 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 arguments1219+Default [signal](https://en.wikipedia.org/wiki/Signal_(IPC)) used to terminate the subprocess.1220 1193-This can be either a name (like `"SIGTERM"`) or a number (like `9`).1221+This can be either a name (like [`'SIGTERM'`](docs/termination.md#sigterm)) or a number (like `9`).1222 1223+[More info.](docs/termination.md#default-signal)1224+1225 #### options.argv01226 1197-Type: `string`1227+Type: `string`\1228+Default: file being executed1229 1199-Explicitly set the value of `argv[0]` sent to the subprocess. This will be set to `file` if not specified.1230+Value of [`argv[0]`](https://nodejs.org/api/process.html#processargv0) sent to the subprocess.1231 1232 #### options.uid1233 1203-Type: `number`1234+Type: `number`\1235+Default: current user identifier1236 1205-Sets the user identity of the subprocess.1237+Sets the [user identifier](https://en.wikipedia.org/wiki/User_identifier) of the subprocess.1238 1239+[More info.](docs/windows.md#uid-and-gid)1240+1241 #### options.gid1242 1209-Type: `number`1243+Type: `number`\1244+Default: current group identifier1245 1211-Sets the group identity of the subprocess.1246+Sets the [group identifier](https://en.wikipedia.org/wiki/Group_identifier) of the subprocess.1247 1248+[More info.](docs/windows.md#uid-and-gid)1249+1250 #### options.windowsVerbatimArguments1251 1252 Type: `boolean`\1216-Default: `false`1253+Default: `true` if the [`shell`](#optionsshell) option is `true`, `false` otherwise1254 1218-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`.1255+If `false`, escapes the command arguments on Windows.1256 1257+[More info.](docs/windows.md#cmdexe-escaping)1258+1259 #### options.windowsHide1260 1261 Type: `boolean`\1262 Default: `true`1263 1225-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.1264+On Windows, do not create a new console window.1265 1227-## Tips1266+[More info.](docs/windows.md#console-window)1267 1229-### Redirect stdin/stdout/stderr to multiple destinations1268+### Transform options1269 1231-The [`stdin`](#optionsstdin), [`stdout`](#optionsstdout) and [`stderr`](#optionsstderr) options can be an array of values.1232-The following example redirects `stdout` to both the terminal and an `output.txt` file, while also retrieving its value programmatically.1270+A 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.1271 1234-```js1235-const {stdout} = await execa('npm', ['install'], {stdout: ['inherit', './output.txt', 'pipe']});1236-console.log(stdout);1237-```1272+A transform is either a [generator function](#transformoptionstransform) or a plain object with the following members.1273 1239-When 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)1275 1241-### Redirect a Node.js stream from/to stdin/stdout/stderr1276+#### transformOptions.transform1277 1243-When 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.1278+Type: `GeneratorFunction<string | Uint8Array | unknown>` | `AsyncGeneratorFunction<string | Uint8Array | unknown>`1279 1245-```1246-TypeError [ERR_INVALID_ARG_VALUE]: The argument 'stdio' is invalid.1247-```1280+Map or [filter](docs/transform.md#filtering) the [input](docs/input.md) or [output](docs/output.md) of the subprocess.1281 1249-This 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`1282+More info [here](docs/transform.md#summary) and [there](docs/transform.md#sharing-state).1283 1253-```diff1254-- await execa(..., {stdout: nodeStream});1255-+ await execa(..., {stdout: [nodeStream, 'pipe']});1256-```1284+#### transformOptions.final1285 1258-### Retry on error1286+Type: `GeneratorFunction<string | Uint8Array | unknown>` | `AsyncGeneratorFunction<string | Uint8Array | unknown>`1287 1260-Safely handle failures by using automatic retries and exponential backoff with the [`p-retry`](https://github.com/sindresorhus/p-retry) package:1288+Create additional lines after the last one.1289 1262-```js1263-import pRetry from 'p-retry';1290+[More info.](docs/transform.md#finalizing)1291 1265-const run = async () => {1266- const results = await execa('curl', ['-sSL', 'https://sindresorhus.com/unicorn']);1267- return results;1268-};1292+#### transformOptions.binary1293 1270-console.log(await pRetry(run, {retries: 5}));1271-```1294+Type: `boolean`\1295+Default: `false`1296 1273-### Cancelling a subprocess1297+If `true`, iterate over arbitrary chunks of `Uint8Array`s instead of line `string`s.1298 1275-```js1276-import {execa} from 'execa';1299+[More info.](docs/binary.md#transforms)1300 1278-const abortController = new AbortController();1279-const subprocess = execa('node', [], {cancelSignal: abortController.signal});1301+#### transformOptions.preserveNewlines1302 1281-setTimeout(() => {1282- abortController.abort();1283-}, 1000);1303+Type: `boolean`\1304+Default: `false`1305 1285-try {1286- await subprocess;1287-} catch (error) {1288- console.log(error.isTerminated); // true1289- console.log(error.isCanceled); // true1290-}1291-```1306+If `true`, keep newlines in each `line` argument. Also, this allows multiple `yield`s to produces a single line.1307 1293-### Execute the current package's binary1308+[More info.](docs/lines.md#transforms)1309 1295-Execa 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.objectMode1311 1297-```js1298-import {getBinPath} from 'get-bin-path';1312+Type: `boolean`\1313+Default: `false`1314 1300-const binPath = await getBinPath();1301-await execa(binPath);1302-```1315+If `true`, allow [`transformOptions.transform`](#transformoptionstransform) and [`transformOptions.final`](#transformoptionsfinal) to return any type, not just `string` or `Uint8Array`.1316 1304-### Ensuring `all` output is interleaved1317+[More info.](docs/transform.md#object-mode)1318 1306-The `subprocess.all` [stream](#subprocessall) and `result.all` [string/`Uint8Array`](#resultall) property are guaranteed to interleave [`stdout`](#resultstdout) and [`stderr`](#resultstderr).1307-1308-However, for performance reasons, the subprocess might buffer and merge multiple simultaneous writes to `stdout` or `stderr`. This prevents proper interleaving.1309-1310-For example, this prints `1 3 2` instead of `1 2 3` because both `console.log()` are merged into a single write.1311-1312-```js1313-import {execa} from 'execa';1314-1315-const {all} = await execa('node', ['example.js'], {all: true});1316-console.log(all);1317-```1318-1319-```js1320-// example.js1321-console.log('1'); // writes to stdout1322-console.error('2'); // writes to stderr1323-console.log('3'); // writes to stdout1324-```1325-1326-This can be worked around by using `setTimeout()`.1327-1328-```js1329-import {setTimeout} from 'timers/promises';1330-1331-console.log('1');1332-console.error('2');1333-await setTimeout(0);1334-console.log('3');1335-```1336-1319 ## Related1320 1321 - [gulp-execa](https://github.com/ehmicky/gulp-execa) - Gulp plugin for Execa1322 - [nvexeca](https://github.com/ehmicky/nvexeca) - Run Execa using any Node.js version5 unmodified lines