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
Provenance
- Commit
466e594- Tree
2b9a536- Author
ehmicky <ehmicky@users.noreply.github.com>- Committer
GitHub <noreply@github.com>- Parent
e085b10
2 files changed+475 added−139 removed
modified:docs/bash.md+475 added-127 removed
4 unmodified lines5 <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)9+This 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)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).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.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.9 unmodified lines33 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.37+Execa 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.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.41+zx 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.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.43+Execa 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.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-49 ## Debugging50 53-Subprocesses can be hard to debug, which is why Execa includes a [`verbose`](#verbose-mode) option.51+Subprocesses 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.52 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).53+Also, 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).54 55 Finally, unlike Bash and zx, which are stateful (options, current directory, etc.), Execa is [purely functional](#current-directory), which also helps with debugging.56 57 ## Examples50 unmodified lines108 // Execa109 await $`npm run build`;110 ```111 112+[More info.](execution.md)113+114 ### Multiline commands115 116 ```sh117 # Bash166 unmodified lines284 ```285 286 ```js287 // zx288-const timeout = '5s';289-await $`npm run init`.timeout(timeout);290-await $`npm run build`.timeout(timeout);291-await $`npm run test`.timeout(timeout);288+const $$ = $({verbose: true});289+290+await $$`npm run init`;291+await $$`npm run build`;292+await $$`npm run test`;293 ```294 295 ```js296 // Execa297 import {$ as $_} from 'execa';298 298-const $ = $_({timeout: 5000});299+const $ = $_({verbose: true});300 301 await $`npm run init`;302 await $`npm run build`;303 await $`npm run test`;9 unmodified lines313 ```314 315 ```js316 // zx316-$.env.EXAMPLE = '1';317-await $`npm run build`;318-delete $.env.EXAMPLE;317+await $({env: {EXAMPLE: '1'}})`npm run build`;318 ```319 320 ```js321 // Execa10 unmodified lines332 ```333 334 ```js335 // zx337-await $`npx tsc --version`;336+await $({preferLocal: true})`tsc --version`;337 ```338 339 ```js340 // Execa342-await $`tsc --version`;341+await $({preferLocal: true})`tsc --version`;342 ```343 344 [More info.](environment.md#local-binaries)345 347-### Builtin utilities346+### Retrieve stdin347 348+```sh349+# Bash350+read content351+```352+353 ```js354 // zx355 const content = await stdin();356 ```4 unmodified lines361 362 const content = await getStdin();363 ```364 365+[More info.](https://github.com/sindresorhus/get-stdin)366+367+### Pass input to stdin368+369+```sh370+# Bash371+cat <<<"example"372+```373+374+```js375+// zx376+$({input: 'example'})`cat`;377+```378+379+```js380+// Execa381+$({input: 'example'})`cat`;382+```383+384+### Pass any input type385+386+```sh387+# Bash only allows passing strings as input388+```389+390+```js391+// zx only allows passing specific input types392+```393+394+```js395+// Execa - main.js396+const ipcInput = [397+ {task: 'lint', ignore: /test\.js/},398+ {task: 'copy', files: new Set(['main.js', 'index.js']),399+}];400+await $({ipcInput})`node build.js`;401+```402+403+```js404+// Execa - build.js405+import {getOneMessage} from 'execa';406+407+const ipcInput = await getOneMessage();408+```409+410+[More info.](ipc.md#send-an-initial-message)411+412+### Return any output type413+414+```sh415+# Bash only allows returning strings as output416+```417+418+```js419+// zx only allows returning specific output types420+```421+422+```js423+// Execa - main.js424+const {ipcOutput} = await $({ipc: true})`node build.js`;425+console.log(ipcOutput[0]); // {kind: 'start', timestamp: date}426+console.log(ipcOutput[1]); // {kind: 'stop', timestamp: date}427+```428+429+```js430+// Execa - build.js431+import {sendMessage} from 'execa';432+433+await sendMessage({kind: 'start', timestamp: new Date()});434+await runBuild();435+await sendMessage({kind: 'stop', timestamp: new Date()});436+```437+438+[More info.](ipc.md#retrieve-all-messages)439+440 ### Printing to stdout441 442 ```sh443 # Bash9 unmodified lines453 // Execa454 console.log('example');455 ```456 378-### Silent stderr457+### Silent stdout458 459 ```sh460 # Bash382-npm run build 2> /dev/null461+npm run build > /dev/null462 ```463 464 ```js465 // zx387-await $`npm run build`.stdio('inherit', 'pipe', 'ignore');466+await $`npm run build`.quiet();467 ```468 469 ```js391-// Execa does not print stdout/stderr by default470+// Execa does not print stdout by default471 await $`npm run build`;472 ```473 395-### Verbose mode474+### Binary output475 476 ```sh477+# Bash usually requires redirecting binary output478+zip -r - input.txt > output.txt479+```480+481+```js482+// zx483+const stdout = await $`zip -r - input.txt`.buffer();484+```485+486+```js487+// Execa488+const {stdout} = await $({encoding: 'buffer'})`zip -r - input.txt`;489+```490+491+[More info.](binary.md#binary-output)492+493+### Verbose mode (single command)494+495+```sh496 # Bash497 set -v498 npm run build499+set +v500 ```501 502 ```js404-// zx >=8503+// zx504 await $`npm run build`.verbose();406-407-// or:408-$.verbose = true;505 ```506 507 ```js508 // Execa509 await $({verbose: 'full'})`npm run build`;510 ```511 416-Or:512+[More info.](debugging.md#verbose-mode)513 514+### Verbose mode (global)515+516+```sh517+# Bash518+set -v519+npm run build520 ```419-NODE_DEBUG=execa node file.js420-```521 422-Which prints:423-522 ```425-[19:49:00.360] [0] $ npm run build523+// zx524+$ zx --verbose file.js525+$ npm run build526 Building...527 Done.528+```529+530+```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 ```537 431-[More info.](debugging.md#verbose-mode)538+[More info.](debugging.md#global-mode)539 540 ### Piping stdout to another command541 542 ```sh2 unmodified lines545 ```546 547 ```js548 // zx442-await $`npm run build | sort | head -n2`;549+await $`npm run build`550+ .pipe($`sort`)551+ .pipe($`head -n2`);552 ```553 554 ```js555 // Execa95 unmodified lines651 ```652 653 [More info.](input.md#file-input)654 655+### Web streams656+657+```js658+// zx does not support web streams659+```660+661+```js662+// Execa663+const response = await fetch('https://example.com');664+await $({stdin: response.body})`npm run build`;665+```666+667+[More info.](streams.md#web-streams)668+669+### Convert to Duplex stream670+671+```js672+// zx does not support converting subprocesses to streams673+```674+675+```js676+// Execa677+import {pipeline} from 'node:stream/promises';678+import {createReadStream, createWriteStream} from 'node:fs';679+680+await pipeline(681+ createReadStream('./input.txt'),682+ $`node ./transform.js`.duplex(),683+ createWriteStream('./output.txt'),684+);685+```686+687+[More info.](streams.md#convert)688+689+### Handle pipeline errors690+691+```sh692+# Bash693+set -e694+npm run crash | sort | head -n2695+```696+697+```js698+// zx699+try {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+```709+710+```js711+// Execa712+try {713+ await $`npm run build`714+ .pipe`sort`715+ .pipe`head -n2`;716+} catch (error) {717+ console.error(error);718+}719+```720+721+[More info.](pipe.md#errors)722+723+### Return all pipeline results724+725+```sh726+# Bash only allows returning each command's exit code727+npm run crash | sort | head -n2728+# 1 0 0729+echo "${PIPESTATUS[@]}"730+```731+732+```js733+// zx only returns the last command's result734+```735+736+```js737+// Execa738+const destinationResult = await execa`npm run build`739+ .pipe`head -n 2`;740+console.log(destinationResult.stdout); // First 2 lines of `npm run build`741+742+const sourceResult = destinationResult.pipedFrom[0];743+console.log(sourceResult.stdout); // Full output of `npm run build`744+```745+746+[More info.](pipe.md#result)747+748+### Split output into lines749+750+```sh751+# Bash752+npm run build | IFS='\n' read -ra lines753+```754+755+```js756+// zx757+const lines = await $`npm run build`.lines();758+```759+760+```js761+// Execa762+const lines = await $({lines: true})`npm run build`;763+```764+765+[More info.](lines.md#simple-splitting)766+767 ### Iterate over output lines768 769 ```sh770 # Bash6 unmodified lines777 done < <(npm run build)778 ```779 780 ```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 ```784 785 ```js786 // Execa5 unmodified lines792 ```793 794 [More info.](lines.md#progressive-splitting)795 575-### Errors796+### Detailed errors797 798 ```sh799 # Bash communicates errors only through the exit code and stderr800 timeout 1 sleep 21 unmodified line802 ```803 804 ```js805 // zx585-const {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: SIGTERM806+await $`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 ```812 813 ```js814 // Execa615-const {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`;815+await $({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 lines848 849 ```js850 // zx851 const {exitCode} = await $`npm run build`.nothrow();668-echo`${exitCode}`;852 ```853 854 ```js855 // Execa856 const {exitCode} = await $({reject: false})`npm run build`;674-console.log(exitCode);857 ```858 859 [More info.](errors.md#exit-code)860 41 unmodified lines902 ```903 904 ```js905 // zx724-cd('project');906+const $$ = $({cwd: 'project'});907 726-// or:727-$.cwd = 'project';908+// Or:909+cd('project');910 ```911 912 ```js913 // Execa1 unmodified line915 ```916 917 [More info.](environment.md#current-directory)918 737-### Multiple current directories738-739-```sh740-# Bash741-pushd project742-pwd743-popd744-pwd745-```746-747-```js748-// zx749-within(async () => {750- cd('project');751- await $`pwd`;752-});753-754-await $`pwd`;755-```756-757-```js758-// Execa759-await $({cwd: 'project'})`pwd`;760-await $`pwd`;761-```762-763-[More info.](environment.md#current-directory)764-919 ### Background subprocess920 921 ```sh922 # Bash923 npm run build &924 ```925 926 ```js773-// zx does not allow setting the `detached` option927+// zx928+await $({detached: true})`npm run build`;929 ```930 931 ```js932 // Execa47 unmodified lines980 ```981 982 [More info.](transform.md)983 829-### Cancelation984+### Signal termination985 986 ```sh987 # Bash988 kill $PID5 unmodified lines994 ```995 996 ```js997 // Execa843-// Can specify an error message and stack trace998+subprocess.kill();999+1000+// Or with an error message and stack trace:1001 subprocess.kill(error);1002+```1003 846-// Or use an `AbortSignal`1004+[More info.](termination.md#signal-termination)1005+1006+### Default signal1007+1008+```sh1009+# Bash does not allow changing the default termination signal1010+```1011+1012+```js1013+// zx only allows changing the signal used for timeouts1014+const $$ = $({timeoutSignal: 'SIGINT'});1015+```1016+1017+```js1018+// Execa1019+const $ = $_({killSignal: 'SIGINT'});1020+```1021+1022+[More info.](termination.md#default-signal)1023+1024+### Cancelation1025+1026+```sh1027+# Bash1028+kill $PID1029+```1030+1031+```js1032+// zx1033 const controller = new AbortController();1034 await $({signal: controller.signal})`node long-script.js`;1035 ```1036 1037+```js1038+// Execa1039+const controller = new AbortController();1040+await $({cancelSignal: controller.signal})`node long-script.js`;1041+```1042+1043 [More info.](termination.md#canceling)1044 1045 ### Interleaved output1046 1 unmodified line1048 # Bash prints stdout and stderr interleaved1049 ```1050 1051 ```js860-// zx separates stdout and stderr861-const {stdout, stderr} = await $`node example.js`;1052+// zx1053+const all = String(await $`node example.js`);1054 ```1055 1056 ```js865-// Execa can interleave stdout and stderr1057+// Execa1058 const {all} = await $({all: true})`node example.js`;1059 ```1060 1061 [More info.](output.md#interleaved-output)16 unmodified lines1078 ```1079 1080 [More info.](termination.md#inter-process-termination)1081 1082+### CLI arguments1083+1084+```js1085+// zx1086+const {myCliFlag} = argv;1087+```1088+1089+```js1090+// Execa1091+import {parseArgs} from 'node:util';1092+1093+const {myCliFlag} = parseArgs({strict: false}).values;1094+```1095+1096+[More info.](https://nodejs.org/api/util.html#utilparseargsconfig)1097+1098+### CLI prompts1099+1100+```sh1101+# Bash1102+read -p "Question? " answer1103+```1104+1105+```js1106+// zx1107+const answer = await question('Question? ');1108+```1109+1110+```js1111+// Execa1112+import input from '@inquirer/input';1113+1114+const answer = await input({message: 'Question?'});1115+```1116+1117+[More info.](https://github.com/SBoudrias/Inquirer.js)1118+1119+### CLI spinner1120+1121+```sh1122+# Bash does not provide with a builtin spinner1123+```1124+1125+```js1126+// zx1127+await spinner(() => $`node script.js`);1128+```1129+1130+```js1131+// Execa1132+import {oraPromise} from 'ora';1133+1134+await oraPromise($`node script.js`);1135+```1136+1137+[More info.](https://github.com/sindresorhus/ora)1138+1139+### Sleep1140+1141+```sh1142+# Bash1143+sleep 51144+```1145+1146+```js1147+// zx1148+await sleep(5000);1149+```1150+1151+```js1152+// Execa1153+import {setTimeout} from 'node:timers/promises';1154+1155+await setTimeout(5000);1156+```1157+1158+[More info.](https://nodejs.org/api/timers.html#timerspromisessettimeoutdelay-value-options)1159+1160+### Globbing1161+1162+```sh1163+# Bash1164+ls packages/*1165+```1166+1167+```js1168+// zx1169+const files = await glob(['packages/*']);1170+```1171+1172+```js1173+// Execa1174+import {glob} from 'node:fs/promises';1175+1176+const files = await Array.fromAsync(glob('packages/*'));1177+```1178+1179+[More info.](https://nodejs.org/api/fs.html#fspromisesglobpattern-options)1180+1181+### Temporary file1182+1183+```js1184+// zx1185+const filePath = tmpfile();1186+```1187+1188+```js1189+// Execa1190+import tempfile from 'tempfile';1191+1192+const filePath = tempfile();1193+```1194+1195+[More info.](https://github.com/sindresorhus/tempfile)1196+1197+### HTTP requests1198+1199+```sh1200+# Bash1201+curl https://github.com1202+```1203+1204+```js1205+// zx1206+await fetch('https://github.com');1207+```1208+1209+```js1210+// Execa1211+await fetch('https://github.com');1212+```1213+1214+[More info.](https://nodejs.org/api/globals.html#fetch)1215+1216+### Retry on error1217+1218+```js1219+// zx1220+await retry(1221+ 5,1222+ () => $`curl -sSL https://sindresorhus.com/unicorn`,1223+)1224+```1225+1226+```js1227+// Execa1228+import pRetry from 'p-retry';1229+1230+await pRetry(1231+ () => $`curl -sSL https://sindresorhus.com/unicorn`,1232+ {retries: 5},1233+);1234+```1235+1236+[More info.](https://github.com/sindresorhus/p-retry)1237+1238 <hr>1239 1240 [**Next**: 🤓 TypeScript](typescript.md)\1241 [**Previous**: 📎 Windows](windows.md)\1 unmodified linemodified:docs/errors.md-12 removed
100 unmodified lines101102103104105106107108109110111112113114115116105106107108109100 unmodified lines // [stdout contents...]}```
## Retry on error
Safely handle failures by using automatic retries and exponential backoff with the [`p-retry`](https://github.com/sindresorhus/p-retry) package.
```jsimport pRetry from 'p-retry';import {execa} from 'execa';
const run = () => execa`curl -sSL https://sindresorhus.com/unicorn`;console.log(await pRetry(run, {retries: 5}));```
<hr>
[**Next**: 🏁 Termination](termination.md)\[**Previous**: 🌐 Environment](environment.md)\[**Top**: Table of contents](../readme.md#documentation)