Add more documentation for `$` (#533)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by ehmicky · committed by GitHub · parent 06287c8 · Browse files · 2 files·+662 added−1 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Trailers
- Co-authored-by: Aaron Casanova <32409546+aaronccasanova@users.noreply.github.com>
- Co-authored-by: Sindre Sorhus <sindresorhus@gmail.com>
Diff stats
2 files+662 added−1 removed
- other:+662 added−1 removed
Provenance
- Commit
9bcfa95- Tree
3052307- Author
ehmicky <ehmicky@users.noreply.github.com>- Committer
GitHub <noreply@github.com>- Parent
06287c8
2 files changed+662 added−1 removed
added:docs/scripts.md+656 added
1+# Node.js scripts2+3+With Execa, you can write scripts with Node.js instead of a shell language. It is [secure](#escaping), [performant](#performance), [simple](#simplicity) and [cross-platform](#shell).4+5+```js6+import {$} from 'execa';7+8+const {stdout: name} = await $`cat package.json`9+ .pipeStdout($`grep name`);10+console.log(name);11+12+const branch = await $`git branch --show-current`;13+await $`dep deploy --branch=${branch}`;14+15+await Promise.all([16+ $`sleep 1`,17+ $`sleep 2`,18+ $`sleep 3`,19+]);20+21+const dirName = 'foo bar';22+await $`mkdir /tmp/${dirName}`;23+```24+25+## Summary26+27+This file describes the differences between Bash, Execa, and [zx](https://github.com/google/zx) (which inspired this feature).28+29+### Flexibility30+31+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).32+33+### Shell34+35+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.36+37+This is more cross-platform. For example, your code works the same on Windows machines without Bash installed.38+39+Also, there is no shell syntax to remember: everything is just plain JavaScript.40+41+If you really need a shell though, the [`shell` option](../readme.md#shell) can be used.42+43+### Simplicity44+45+Execa's scripting API mostly consists of only two methods: [`` $`command` ``](../readme.md#command) and [`$(options)`](../readme.md#options).46+47+[No special binary](#main-binary) is recommended, no [global variable](#global-variables) is injected: scripts are regular Node.js files.48+49+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-processes): [`pid`](#pid), [IPC](https://nodejs.org/api/child_process.html#subprocesssendmessage-sendhandle-options-callback), [`unref()`](https://nodejs.org/api/child_process.html#subprocessunref), [`detached`](https://nodejs.org/api/child_process.html#child_processspawncommand-args-options), [`uid`](https://nodejs.org/api/child_process.html#child_processspawncommand-args-options), [`gid`](https://nodejs.org/api/child_process.html#child_processspawncommand-args-options), [`signal`](https://nodejs.org/api/child_process.html#child_processspawncommand-args-options), etc.50+51+### Modularity52+53+zx includes many builtin utilities: `fetch()`, `question()`, `sleep()`, `stdin()`, `retry()`, `spinner()`, `chalk`, `fs-extra`, `os`, `path`, `globby`, `yaml`, `minimist`, `which`, Markdown scripts, remote scripts.54+55+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.56+57+### Performance58+59+Spawning a shell for every command comes at a performance cost, which Execa avoids.60+61+Also, [local binaries](#local-binaries) can be directly executed without using `npx`.62+63+### Debugging64+65+Child processes can be hard to debug, which is why Execa includes a [`verbose` option](#verbose-mode).66+67+Also, Execa's error messages and [properties](#errors) are very detailed to make it clear to determine why a process failed.68+69+Finally, unlike Bash and zx, which are stateful (options, current directory, etc.), Execa is [purely functional](#current-directory), which also helps with debugging.70+71+## Details72+73+### Main binary74+75+```sh76+# Bash77+bash file.sh78+```79+80+```js81+// zx82+zx file.js83+84+// or a shebang can be used:85+// #!/usr/bin/env zx86+```87+88+```js89+// Execa scripts are just regular Node.js files90+node file.js91+```92+93+### Global variables94+95+```js96+// zx97+await $`echo example`;98+```99+100+```js101+// Execa102+import {$} from 'execa';103+104+await $`echo example`;105+```106+107+### Command execution108+109+```sh110+# Bash111+echo example112+```113+114+```js115+// zx116+await $`echo example`;117+```118+119+```js120+// Execa121+await $`echo example`;122+```123+124+### Subcommands125+126+```sh127+# Bash128+echo "$(echo example)"129+```130+131+```js132+// zx133+const example = await $`echo example`;134+await $`echo ${example}`;135+```136+137+```js138+// Execa139+const example = await $`echo example`;140+await $`echo ${example}`;141+```142+143+### Parallel commands144+145+```sh146+# Bash147+echo one &148+echo two &149+```150+151+```js152+// zx153+await Promise.all([$`echo one`, $`echo two`]);154+```155+156+```js157+// Execa158+await Promise.all([$`echo one`, $`echo two`]);159+```160+161+### Serial commands162+163+```sh164+# Bash165+echo one && echo two166+```167+168+```js169+// zx170+await $`echo one && echo two`;171+```172+173+```js174+// Execa175+await $`echo one`;176+await $`echo two`;177+```178+179+### Local binaries180+181+```sh182+# Bash183+npx tsc --version184+```185+186+```js187+// zx188+await $`npx tsc --version`;189+```190+191+```js192+// Execa193+await $`tsc --version`;194+```195+196+### Builtin utilities197+198+```js199+// zx200+const content = await stdin();201+```202+203+```js204+// Execa205+import getStdin from 'get-stdin';206+207+const content = await getStdin();208+```209+210+### Variable substitution211+212+```sh213+# Bash214+echo $LANG215+```216+217+```js218+// zx219+await $`echo $LANG`;220+```221+222+```js223+// Execa224+await $`echo ${process.env.LANG}`;225+```226+227+### Environment variables228+229+```sh230+# Bash231+EXAMPLE=1 example_command232+```233+234+```js235+// zx236+$.env.EXAMPLE = '1';237+await $`example_command`;238+delete $.env.EXAMPLE;239+```240+241+```js242+// Execa243+await $({env: {EXAMPLE: '1'}})`example_command`;244+```245+246+### Escaping247+248+```sh249+# Bash250+echo 'one two'251+```252+253+```js254+// zx255+await $`echo ${'one two'}`;256+```257+258+```js259+// Execa260+await $`echo ${'one two'}`;261+```262+263+### Escaping multiple arguments264+265+```sh266+# Bash267+echo 'one two' '$'268+```269+270+```js271+// zx272+await $`echo ${['one two', '$']}`;273+```274+275+```js276+// Execa277+await $`echo ${['one two', '$']}`;278+```279+280+### Current filename281+282+```sh283+# Bash284+echo "$(basename "$0")"285+```286+287+```js288+// zx289+await $`echo ${__filename}`;290+```291+292+```js293+// Execa294+import {fileURLToPath} from 'node:url';295+import path from 'node:path';296+297+const __filename = path.basename(fileURLToPath(import.meta.url));298+299+await $`echo ${__filename}`;300+```301+302+### Verbose mode303+304+```sh305+# Bash306+set -v307+echo example308+```309+310+```js311+// zx >=8312+await $`echo example`.verbose();313+314+// or:315+$.verbose = true;316+```317+318+```js319+// Execa320+const $$ = $({verbose: true});321+await $$`echo example`;322+```323+324+Or:325+326+```327+NODE_DEBUG=execa node file.js328+```329+330+### Current directory331+332+```sh333+# Bash334+cd project335+```336+337+```js338+// zx339+cd('project');340+341+// or:342+$.cwd = 'project';343+```344+345+```js346+// Execa347+const $$ = $({cwd: 'project'});348+```349+350+### Multiple current directories351+352+```sh353+# Bash354+pushd project355+pwd356+popd357+pwd358+```359+360+```js361+// zx362+within(async () => {363+ cd('project');364+ await $`pwd`;365+});366+367+await $`pwd`;368+```369+370+```js371+// Execa372+await $({cwd: 'project'})`pwd`;373+await $`pwd`;374+```375+376+### Exit codes377+378+```sh379+# Bash380+false381+echo $?382+```383+384+```js385+// zx386+const {exitCode} = await $`false`.nothrow();387+echo`${exitCode}`;388+```389+390+```js391+// Execa392+const {exitCode} = await $({reject: false})`false`;393+console.log(exitCode);394+```395+396+### Timeouts397+398+```sh399+# Bash400+timeout 5 echo example401+```402+403+```js404+// zx405+await $`echo example`.timeout('5s');406+```407+408+```js409+// Execa410+await $({timeout: 5000})`echo example`;411+```412+413+### PID414+415+```sh416+# Bash417+echo example &418+echo $!419+```420+421+```js422+// zx does not return `childProcess.pid`423+```424+425+```js426+// Execa427+const {pid} = $`echo example`;428+```429+430+### Errors431+432+```sh433+# Bash communicates errors only through the exit code and stderr434+timeout 1 sleep 2435+echo $?436+```437+438+```js439+// zx440+const {441+ stdout,442+ stderr,443+ exitCode,444+ signal,445+} = await $`sleep 2`.timeout('1s');446+// file:///home/me/Desktop/node_modules/zx/build/core.js:146447+// let output = new ProcessOutput(code, signal, stdout, stderr, combined, message);448+// ^449+// ProcessOutput [Error]:450+// at file:///home/me/Desktop/example.js:2:20451+// exit code: null452+// signal: SIGTERM453+// at ChildProcess.<anonymous> (file:///home/me/Desktop/node_modules/zx/build/core.js:146:26)454+// at ChildProcess.emit (node:events:512:28)455+// at maybeClose (node:internal/child_process:1098:16)456+// at Socket.<anonymous> (node:internal/child_process:456:11)457+// at Socket.emit (node:events:512:28)458+// at Pipe.<anonymous> (node:net:316:12)459+// at Pipe.callbackTrampoline (node:internal/async_hooks:130:17) {460+// _code: null,461+// _signal: 'SIGTERM',462+// _stdout: '',463+// _stderr: '',464+// _combined: ''465+// }466+```467+468+```js469+// Execa470+const {471+ stdout,472+ stderr,473+ exitCode,474+ signal,475+ signalDescription,476+ originalMessage,477+ shortMessage,478+ command,479+ escapedCommand,480+ failed,481+ timedOut,482+ isCanceled,483+ killed,484+ // and other error-related properties: code, etc.485+} = await $({timeout: 1})`sleep 2`;486+// file:///home/me/code/execa/lib/kill.js:60487+// reject(Object.assign(new Error('Timed out'), {timedOut: true, signal}));488+// ^489+// Error: Command timed out after 1 milliseconds: sleep 2490+// Timed out491+// at file:///home/me/Desktop/example.js:2:20492+// timedOut: true,493+// signal: 'SIGTERM',494+// originalMessage: 'Timed out',495+// shortMessage: 'Command timed out after 1 milliseconds: sleep 2\nTimed out',496+// command: 'sleep 2',497+// escapedCommand: 'sleep 2',498+// exitCode: undefined,499+// signalDescription: 'Termination',500+// stdout: '',501+// stderr: '',502+// failed: true,503+// isCanceled: false,504+// killed: false505+// }506+```507+508+### Shared options509+510+```sh511+# Bash512+options="timeout 5"513+$options echo one514+$options echo two515+$options echo three516+```517+518+```js519+// zx520+const timeout = '5s';521+await $`echo one`.timeout(timeout);522+await $`echo two`.timeout(timeout);523+await $`echo three`.timeout(timeout);524+```525+526+```js527+// Execa528+const $$ = $({timeout: 5000});529+await $$`echo one`;530+await $$`echo two`;531+await $$`echo three`;532+```533+534+### Background processes535+536+```sh537+# Bash538+echo one &539+```540+541+```js542+// zx does not allow setting the `detached` option543+```544+545+```js546+// Execa547+await $({detached: true})`echo one`;548+```549+550+### Printing to stdout551+552+```sh553+# Bash554+echo example555+```556+557+```js558+// zx559+echo`example`;560+```561+562+```js563+// Execa564+console.log('example');565+```566+567+### Piping stdout to another command568+569+```sh570+# Bash571+echo example | cat572+```573+574+```js575+// zx576+await $`echo example | cat`;577+```578+579+```js580+// Execa581+await $`echo example`.pipeStdout($`cat`);582+```583+584+### Piping stdout and stderr to another command585+586+```sh587+# Bash588+echo example |& cat589+```590+591+```js592+// zx593+const echo = $`echo example`;594+const cat = $`cat`;595+echo.pipe(cat)596+echo.stderr.pipe(cat.stdin);597+await Promise.all([echo, cat]);598+```599+600+```js601+// Execa602+await $`echo example`.pipeAll($`cat`);603+```604+605+### Piping stdout to a file606+607+```sh608+# Bash609+echo example > file.txt610+```611+612+```js613+// zx614+await $`echo example`.pipe(fs.createWriteStream('file.txt'));615+```616+617+```js618+// Execa619+await $`echo example`.pipeStdout('file.txt');620+```621+622+### Piping stdin from a file623+624+```sh625+# Bash626+echo example < file.txt627+```628+629+```js630+// zx631+const cat = $`cat`632+fs.createReadStream('file.txt').pipe(cat.stdin)633+await cat634+```635+636+```js637+// Execa638+await $`cat`.pipeStdin('file.txt');639+```640+641+### Silent stderr642+643+```sh644+# Bash645+echo example 2> /dev/null646+```647+648+```js649+// zx650+await $`echo example`.stdio('inherit', 'pipe', 'ignore');651+```652+653+```js654+// Execa does not forward stdout/stderr by default655+await $`echo example`;656+```modified:readme.md+6 added-1 removed
11 unmodified lines12 13 This package improves [`child_process`](https://nodejs.org/api/child_process.html) methods with:14 15 - Promise interface.16+- [Scripts interface](#scripts-interface).17 - [Strips the final newline](#stripfinalnewline) from the output so you don't have to do `stdout.trim()`.18 - Supports [shebang](https://en.wikipedia.org/wiki/Shebang_(Unix)) binaries cross-platform.19 - [Improved Windows support.](https://github.com/IndigoUnited/node-cross-spawn#why)20 - Higher max buffer. 100 MB instead of 200 KB.19 unmodified lines40 console.log(stdout);41 //=> 'unicorns'42 ```43 43-### Using the tagged templates API44+### Scripts interface45 46+For more information, please see [this page](docs/scripts.md).47+48 #### Basic49 50 ```js51 import {$} from 'execa';282 unmodified lines334 As a convenience, the result from previous [`` $`command` ``](#command) or [`` $.sync`command` ``](#synccommand) calls can be used as template expressions in subsequent commands and `$`/`$.sync` will use the `stdout` value. See the example above [with results from `$` or `$.sync`](#with-results-from--or-sync) for more details.335 336 Returns a `Promise` that resolves or rejects with a [`childProcessResult`](#childProcessResult).337 338+For more information, please see [this page](docs/scripts.md).339+340 ### $.sync\`command\`341 342 Same as [$\`command\`](#command) but synchronous like [`execaSync()`](#execasyncfile-arguments-options).343 465 unmodified lines