Skip to content
Myr

Improve bash vs zx vs Execa documentation (#1100)

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

authored by ehmicky · committed by GitHub · parent e085b10 · Browse files · 2 files+475 added−139 removed
This commit

State

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

Diff stats

2 files+475 added−139 removed

  • other:+475 added−139 removed

2 files+475 added−139 removed

modified:docs/bash.md+475 added-127 removed
4 unmodified lines
5<br>67# 🔍 Differences with Bash and zx89This page describes the differences between [Bash](https://en.wikipedia.org/wiki/Bash_(Unix_shell)), Execa, and [zx](https://github.com/google/zx) (which inspired this feature). Execa intends to be more:10- [Performant](#performance)9This page describes the differences between [Bash](https://en.wikipedia.org/wiki/Bash_(Unix_shell)), Execa, and [zx](https://github.com/google/zx). Execa intends to be more:10- [Simple](#simplicity): minimalistic API, no [globals](#global-variables), no [binary](#main-binary), no builtin CLI utilities.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.13- [Featureful](#simplicity): all Execa features are available ([text lines iteration](#iterate-over-output-lines), [advanced piping](#piping-stdout-to-another-command), [simple IPC](#ipc), [passing any input type](#pass-any-input-type), [returning any output type](#return-any-output-type), [transforms](#transforms), [web streams](#web-streams), [convert to Duplex stream](#convert-to-duplex-stream), [cleanup on exit](termination.md#current-process-exit), [forceful termination](termination.md#forceful-termination), and [more](../readme.md#documentation)).14- [Easy to debug](#debugging): [verbose mode](#verbose-mode-single-command), [detailed errors](#detailed-errors), [messages and stack traces](#cancelation), stateless API.15- [Performant](#performance)1617## Flexibility1819Unlike shell languages like Bash, libraries like Execa and zx enable you to write scripts with a more featureful programming language (JavaScript). This allows complex logic (such as [parallel execution](#parallel-commands)) to be expressed easily. This also lets you use [any Node.js package](#builtin-utilities).19Unlike 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.2021## Shell2223The main difference between Execa and zx is that Execa does not require any shell. Shell-specific keywords and features are [written in JavaScript](#variable-substitution) instead.
9 unmodified lines
33Execa's scripting API mostly consists of only two methods: [`` $`command` ``](shell.md) and [`$(options)`](execution.md#globalshared-options).3435[No special binary](#main-binary) is recommended, no [global variable](#global-variables) is injected: scripts are regular Node.js files.3637Execa is a thin wrapper around the core Node.js [`child_process` module](https://nodejs.org/api/child_process.html). Unlike zx, it lets you use [any of its native features](#background-subprocess): [`pid`](#pid), [IPC](ipc.md), [`unref()`](https://nodejs.org/api/child_process.html#subprocessunref), [`detached`](environment.md#background-subprocess), [`uid`](windows.md#uid-and-gid), [`gid`](windows.md#uid-and-gid), [`cancelSignal`](termination.md#canceling), etc.37Execa is a thin wrapper around the core Node.js [`child_process` module](https://nodejs.org/api/child_process.html). It lets you use any of its native features.3839## Modularity4041zx includes many builtin utilities: `fetch()`, `question()`, `sleep()`, `stdin()`, `retry()`, `spinner()`, `chalk`, `fs-extra`, `os`, `path`, `globby`, `yaml`, `minimist`, `which`, Markdown scripts, remote scripts.41zx includes many builtin utilities: [`fetch()`](#http-requests), [`question()`](#cli-prompts), [`sleep()`](#sleep), [`echo()`](#printing-to-stdout), [`stdin()`](#retrieve-stdin), [`retry()`](#retry-on-error), [`spinner()`](#cli-spinner), [`globby`](#globbing), [`chalk`](https://github.com/chalk/chalk), [`fs`](https://github.com/jprichardson/node-fs-extra), [`os`](https://nodejs.org/api/os.html), [`path`](https://nodejs.org/api/path.html), [`yaml`](https://github.com/eemeli/yaml), [`which`](https://github.com/npm/node-which), [`ps`](https://github.com/webpod/ps), [`tmpfile()`](#temporary-file), [`argv`](#cli-arguments), Markdown scripts, remote scripts.4243Execa does not include [any utility](#builtin-utilities): it focuses on being small and modular instead. Any Node.js package can be used in your scripts.43Execa does not include any utility: it focuses on being small and modular instead. [Any Node.js package](https://github.com/sindresorhus/awesome-nodejs#command-line-utilities) can be used in your scripts.4445## Performance4647Spawning a shell for every command comes at a performance cost, which Execa avoids.4849Also, [local binaries](#local-binaries) can be directly executed without using `npx`.5049## Debugging5053Subprocesses can be hard to debug, which is why Execa includes a [`verbose`](#verbose-mode) option.51Subprocesses can be hard to debug, which is why Execa includes a [`verbose`](#verbose-mode-single-command) option. It includes [more information](debugging.md#full-mode) than zx: timestamps, command completion and duration, interleaved commands, IPC messages.5255Also, 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).53Also, Execa's error messages and [properties](#detailed-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).5455Finally, unlike Bash and zx, which are stateful (options, current directory, etc.), Execa is [purely functional](#current-directory), which also helps with debugging.5657## Examples
50 unmodified lines
108// Execa109await $`npm run build`;110```111112[More info.](execution.md)113114### Multiline commands115116```sh117# Bash
166 unmodified lines
284```285286```js287// zx288const timeout = '5s';289await $`npm run init`.timeout(timeout);290await $`npm run build`.timeout(timeout);291await $`npm run test`.timeout(timeout);288const $$ = $({verbose: true});289290await $$`npm run init`;291await $$`npm run build`;292await $$`npm run test`;293```294295```js296// Execa297import {$ as $_} from 'execa';298298const $ = $_({timeout: 5000});299const $ = $_({verbose: true});300301await $`npm run init`;302await $`npm run build`;303await $`npm run test`;
9 unmodified lines
313```314315```js316// zx316$.env.EXAMPLE = '1';317await $`npm run build`;318delete $.env.EXAMPLE;317await $({env: {EXAMPLE: '1'}})`npm run build`;318```319320```js321// Execa
10 unmodified lines
332```333334```js335// zx337await $`npx tsc --version`;336await $({preferLocal: true})`tsc --version`;337```338339```js340// Execa342await $`tsc --version`;341await $({preferLocal: true})`tsc --version`;342```343344[More info.](environment.md#local-binaries)345347### Builtin utilities346### Retrieve stdin347348```sh349# Bash350read content351```352353```js354// zx355const content = await stdin();356```
4 unmodified lines
361362const content = await getStdin();363```364365[More info.](https://github.com/sindresorhus/get-stdin)366367### Pass input to stdin368369```sh370# Bash371cat <<<"example"372```373374```js375// zx376$({input: 'example'})`cat`;377```378379```js380// Execa381$({input: 'example'})`cat`;382```383384### Pass any input type385386```sh387# Bash only allows passing strings as input388```389390```js391// zx only allows passing specific input types392```393394```js395// Execa - main.js396const ipcInput = [397 {task: 'lint', ignore: /test\.js/},398 {task: 'copy', files: new Set(['main.js', 'index.js']),399}];400await $({ipcInput})`node build.js`;401```402403```js404// Execa - build.js405import {getOneMessage} from 'execa';406407const ipcInput = await getOneMessage();408```409410[More info.](ipc.md#send-an-initial-message)411412### Return any output type413414```sh415# Bash only allows returning strings as output416```417418```js419// zx only allows returning specific output types420```421422```js423// Execa - main.js424const {ipcOutput} = await $({ipc: true})`node build.js`;425console.log(ipcOutput[0]); // {kind: 'start', timestamp: date}426console.log(ipcOutput[1]); // {kind: 'stop', timestamp: date}427```428429```js430// Execa - build.js431import {sendMessage} from 'execa';432433await sendMessage({kind: 'start', timestamp: new Date()});434await runBuild();435await sendMessage({kind: 'stop', timestamp: new Date()});436```437438[More info.](ipc.md#retrieve-all-messages)439440### Printing to stdout441442```sh443# Bash
9 unmodified lines
453// Execa454console.log('example');455```456378### Silent stderr457### Silent stdout458459```sh460# Bash382npm run build 2> /dev/null461npm run build > /dev/null462```463464```js465// zx387await $`npm run build`.stdio('inherit', 'pipe', 'ignore');466await $`npm run build`.quiet();467```468469```js391// Execa does not print stdout/stderr by default470// Execa does not print stdout by default471await $`npm run build`;472```473395### Verbose mode474### Binary output475476```sh477# Bash usually requires redirecting binary output478zip -r - input.txt > output.txt479```480481```js482// zx483const stdout = await $`zip -r - input.txt`.buffer();484```485486```js487// Execa488const {stdout} = await $({encoding: 'buffer'})`zip -r - input.txt`;489```490491[More info.](binary.md#binary-output)492493### Verbose mode (single command)494495```sh496# Bash497set -v498npm run build499set +v500```501502```js404// zx >=8503// zx504await $`npm run build`.verbose();406407// or:408$.verbose = true;505```506507```js508// Execa509await $({verbose: 'full'})`npm run build`;510```511416Or:512[More info.](debugging.md#verbose-mode)513514### Verbose mode (global)515516```sh517# Bash518set -v519npm run build520```419NODE_DEBUG=execa node file.js420```521422Which prints:423522```425[19:49:00.360] [0] $ npm run build523// zx524$ zx --verbose file.js525$ npm run build526Building...527Done.528```529530```531$ NODE_DEBUG=execa node file.js532[19:49:00.360] [0] $ npm run build533[19:49:00.360] [0] Building...534[19:49:00.360] [0] Done.535[19:49:00.383] [0] √ (done in 23ms)536```537431[More info.](debugging.md#verbose-mode)538[More info.](debugging.md#global-mode)539540### Piping stdout to another command541542```sh
2 unmodified lines
545```546547```js548// zx442await $`npm run build | sort | head -n2`;549await $`npm run build`550 .pipe($`sort`)551 .pipe($`head -n2`);552```553554```js555// Execa
95 unmodified lines
651```652653[More info.](input.md#file-input)654655### Web streams656657```js658// zx does not support web streams659```660661```js662// Execa663const response = await fetch('https://example.com');664await $({stdin: response.body})`npm run build`;665```666667[More info.](streams.md#web-streams)668669### Convert to Duplex stream670671```js672// zx does not support converting subprocesses to streams673```674675```js676// Execa677import {pipeline} from 'node:stream/promises';678import {createReadStream, createWriteStream} from 'node:fs';679680await pipeline(681 createReadStream('./input.txt'),682 $`node ./transform.js`.duplex(),683 createWriteStream('./output.txt'),684);685```686687[More info.](streams.md#convert)688689### Handle pipeline errors690691```sh692# Bash693set -e694npm run crash | sort | head -n2695```696697```js698// zx699try {700 await $`npm run crash`701 .pipe($`sort`)702 .pipe($`head -n2`);703// This is never reached.704// The process crashes instead.705} catch (error) {706 console.error(error);707}708```709710```js711// Execa712try {713 await $`npm run build`714 .pipe`sort`715 .pipe`head -n2`;716} catch (error) {717 console.error(error);718}719```720721[More info.](pipe.md#errors)722723### Return all pipeline results724725```sh726# Bash only allows returning each command's exit code727npm run crash | sort | head -n2728# 1 0 0729echo "${PIPESTATUS[@]}"730```731732```js733// zx only returns the last command's result734```735736```js737// Execa738const destinationResult = await execa`npm run build`739 .pipe`head -n 2`;740console.log(destinationResult.stdout); // First 2 lines of `npm run build`741742const sourceResult = destinationResult.pipedFrom[0];743console.log(sourceResult.stdout); // Full output of `npm run build`744```745746[More info.](pipe.md#result)747748### Split output into lines749750```sh751# Bash752npm run build | IFS='\n' read -ra lines753```754755```js756// zx757const lines = await $`npm run build`.lines();758```759760```js761// Execa762const lines = await $({lines: true})`npm run build`;763```764765[More info.](lines.md#simple-splitting)766767### Iterate over output lines768769```sh770# Bash
6 unmodified lines
777done < <(npm run build)778```779780```js560// zx does not allow proper iteration.561// For example, the iteration does not handle subprocess errors.781// zx does not allow easily iterating over output lines.782// Also, the iteration does not handle subprocess errors.783```784785```js786// Execa
5 unmodified lines
792```793794[More info.](lines.md#progressive-splitting)795575### Errors796### Detailed errors797798```sh799# Bash communicates errors only through the exit code and stderr800timeout 1 sleep 2
1 unmodified line
802```803804```js805// zx585const {586 stdout,587 stderr,588 exitCode,589 signal,590} = await $`sleep 2`.timeout('1s');591// file:///home/me/Desktop/node_modules/zx/build/core.js:146592// let output = new ProcessOutput(code, signal, stdout, stderr, combined, message);593// ^594// ProcessOutput [Error]:595// at file:///home/me/Desktop/example.js:2:20596// exit code: null597// signal: SIGTERM806await $`sleep 2`.timeout('1ms');807// Error:808// at file:///home/me/Desktop/example.js:6:12809// exit code: null810// signal: SIGTERM598// at ChildProcess.<anonymous> (file:///home/me/Desktop/node_modules/zx/build/core.js:146:26)599// at ChildProcess.emit (node:events:512:28)600// at maybeClose (node:internal/child_process:1098:16)601// at Socket.<anonymous> (node:internal/child_process:456:11)602// at Socket.emit (node:events:512:28)603// at Pipe.<anonymous> (node:net:316:12)604// at Pipe.callbackTrampoline (node:internal/async_hooks:130:17) {605// _code: null,606// _signal: 'SIGTERM',607// _stdout: '',608// _stderr: '',609// _combined: ''610// }811```812813```js814// Execa615const {616 stdout,617 stderr,618 exitCode,619 signal,620 signalDescription,621 originalMessage,622 shortMessage,623 command,624 escapedCommand,625 failed,626 timedOut,627 isCanceled,628 isTerminated,629 isMaxBuffer,630 // and other error-related properties: code, etc.631} = await $({timeout: 1})`sleep 2`;815await $({timeout: 1})`sleep 2`;816// ExecaError: Command timed out after 1 milliseconds: sleep 2817// at file:///home/me/Desktop/example.js:2:20818// at ... {819// shortMessage: 'Command timed out after 1 milliseconds: sleep 2\nTimed out',
28 unmodified lines
848849```js850// zx851const {exitCode} = await $`npm run build`.nothrow();668echo`${exitCode}`;852```853854```js855// Execa856const {exitCode} = await $({reject: false})`npm run build`;674console.log(exitCode);857```858859[More info.](errors.md#exit-code)860
41 unmodified lines
902```903904```js905// zx724cd('project');906const $$ = $({cwd: 'project'});907726// or:727$.cwd = 'project';908// Or:909cd('project');910```911912```js913// Execa
1 unmodified line
915```916917[More info.](environment.md#current-directory)918737### Multiple current directories738739```sh740# Bash741pushd project742pwd743popd744pwd745```746747```js748// zx749within(async () => {750 cd('project');751 await $`pwd`;752});753754await $`pwd`;755```756757```js758// Execa759await $({cwd: 'project'})`pwd`;760await $`pwd`;761```762763[More info.](environment.md#current-directory)764919### Background subprocess920921```sh922# Bash923npm run build &924```925926```js773// zx does not allow setting the `detached` option927// zx928await $({detached: true})`npm run build`;929```930931```js932// Execa
47 unmodified lines
980```981982[More info.](transform.md)983829### Cancelation984### Signal termination985986```sh987# Bash988kill $PID
5 unmodified lines
994```995996```js997// Execa843// Can specify an error message and stack trace998subprocess.kill();9991000// Or with an error message and stack trace:1001subprocess.kill(error);1002```1003846// Or use an `AbortSignal`1004[More info.](termination.md#signal-termination)10051006### Default signal10071008```sh1009# Bash does not allow changing the default termination signal1010```10111012```js1013// zx only allows changing the signal used for timeouts1014const $$ = $({timeoutSignal: 'SIGINT'});1015```10161017```js1018// Execa1019const $ = $_({killSignal: 'SIGINT'});1020```10211022[More info.](termination.md#default-signal)10231024### Cancelation10251026```sh1027# Bash1028kill $PID1029```10301031```js1032// zx1033const controller = new AbortController();1034await $({signal: controller.signal})`node long-script.js`;1035```10361037```js1038// Execa1039const controller = new AbortController();1040await $({cancelSignal: controller.signal})`node long-script.js`;1041```10421043[More info.](termination.md#canceling)10441045### Interleaved output1046
1 unmodified line
1048# Bash prints stdout and stderr interleaved1049```10501051```js860// zx separates stdout and stderr861const {stdout, stderr} = await $`node example.js`;1052// zx1053const all = String(await $`node example.js`);1054```10551056```js865// Execa can interleave stdout and stderr1057// Execa1058const {all} = await $({all: true})`node example.js`;1059```10601061[More info.](output.md#interleaved-output)
16 unmodified lines
1078```10791080[More info.](termination.md#inter-process-termination)10811082### CLI arguments10831084```js1085// zx1086const {myCliFlag} = argv;1087```10881089```js1090// Execa1091import {parseArgs} from 'node:util';10921093const {myCliFlag} = parseArgs({strict: false}).values;1094```10951096[More info.](https://nodejs.org/api/util.html#utilparseargsconfig)10971098### CLI prompts10991100```sh1101# Bash1102read -p "Question? " answer1103```11041105```js1106// zx1107const answer = await question('Question? ');1108```11091110```js1111// Execa1112import input from '@inquirer/input';11131114const answer = await input({message: 'Question?'});1115```11161117[More info.](https://github.com/SBoudrias/Inquirer.js)11181119### CLI spinner11201121```sh1122# Bash does not provide with a builtin spinner1123```11241125```js1126// zx1127await spinner(() => $`node script.js`);1128```11291130```js1131// Execa1132import {oraPromise} from 'ora';11331134await oraPromise($`node script.js`);1135```11361137[More info.](https://github.com/sindresorhus/ora)11381139### Sleep11401141```sh1142# Bash1143sleep 51144```11451146```js1147// zx1148await sleep(5000);1149```11501151```js1152// Execa1153import {setTimeout} from 'node:timers/promises';11541155await setTimeout(5000);1156```11571158[More info.](https://nodejs.org/api/timers.html#timerspromisessettimeoutdelay-value-options)11591160### Globbing11611162```sh1163# Bash1164ls packages/*1165```11661167```js1168// zx1169const files = await glob(['packages/*']);1170```11711172```js1173// Execa1174import {glob} from 'node:fs/promises';11751176const files = await Array.fromAsync(glob('packages/*'));1177```11781179[More info.](https://nodejs.org/api/fs.html#fspromisesglobpattern-options)11801181### Temporary file11821183```js1184// zx1185const filePath = tmpfile();1186```11871188```js1189// Execa1190import tempfile from 'tempfile';11911192const filePath = tempfile();1193```11941195[More info.](https://github.com/sindresorhus/tempfile)11961197### HTTP requests11981199```sh1200# Bash1201curl https://github.com1202```12031204```js1205// zx1206await fetch('https://github.com');1207```12081209```js1210// Execa1211await fetch('https://github.com');1212```12131214[More info.](https://nodejs.org/api/globals.html#fetch)12151216### Retry on error12171218```js1219// zx1220await retry(1221 5,1222 () => $`curl -sSL https://sindresorhus.com/unicorn`,1223)1224```12251226```js1227// Execa1228import pRetry from 'p-retry';12291230await pRetry(1231 () => $`curl -sSL https://sindresorhus.com/unicorn`,1232 {retries: 5},1233);1234```12351236[More info.](https://github.com/sindresorhus/p-retry)12371238<hr>12391240[**Next**: 🤓 TypeScript](typescript.md)\1241[**Previous**: 📎 Windows](windows.md)\
1 unmodified line
modified:docs/errors.md-12 removed