Skip to content
Myr

scripts.md

This file

Path

docs/scripts.md

703 lines · 11.2 KiB · Markdown

Last changed by

Allow newlines in `$` (#843)ehmickybefore adoption1315486

History of this file

Take it

The walk stopped after 200 commits: lines older than db2ad9a point at it.

Improve main method documentation (#545)ehmickybefore adoptiondb2ad9a

lines 1–8why, one step back
1# Node.js scripts
23With 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).45```js6import {$} from 'execa';78const {stdout: name} = await $`cat package.json`

`.pipe()` shortcut for `$` (#840)ehmickybefore adoption316f562

line 9why, one step back
9 .pipe`grep name`;

Improve main method documentation (#545)ehmickybefore adoptiondb2ad9a

lines 10–123why, one step back
10console.log(name);
1112const branch = await $`git branch --show-current`;13await $`dep deploy --branch=${branch}`;1415await Promise.all([16 $`sleep 1`,17 $`sleep 2`,18 $`sleep 3`,19]);2021const dirName = 'foo bar';22await $`mkdir /tmp/${dirName}`;23```2425## Summary2627This file describes the differences between Bash, Execa, and [zx](https://github.com/google/zx) (which inspired this feature).2829### Flexibility3031Unlike 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).3233### Shell3435The 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.3637This is more cross-platform. For example, your code works the same on Windows machines without Bash installed.3839Also, there is no shell syntax to remember: everything is just plain JavaScript.4041If you really need a shell though, the [`shell` option](../readme.md#shell) can be used.4243### Simplicity4445Execa's scripting API mostly consists of only two methods: [`` $`command` ``](../readme.md#command) and [`$(options)`](../readme.md#options).4647[No special binary](#main-binary) is recommended, no [global variable](#global-variables) is injected: scripts are regular Node.js files.4849Execa 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.5051### Modularity5253zx includes many builtin utilities: `fetch()`, `question()`, `sleep()`, `stdin()`, `retry()`, `spinner()`, `chalk`, `fs-extra`, `os`, `path`, `globby`, `yaml`, `minimist`, `which`, Markdown scripts, remote scripts.5455Execa 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.5657### Performance5859Spawning a shell for every command comes at a performance cost, which Execa avoids.6061Also, [local binaries](#local-binaries) can be directly executed without using `npx`.6263### Debugging6465Child processes can be hard to debug, which is why Execa includes a [`verbose` option](#verbose-mode).6667Also, Execa's error messages and [properties](#errors) are very detailed to make it clear to determine why a process failed.6869Finally, unlike Bash and zx, which are stateful (options, current directory, etc.), Execa is [purely functional](#current-directory), which also helps with debugging.7071## Details7273### Main binary7475```sh76# Bash77bash file.sh78```7980```js81// zx82zx file.js8384// or a shebang can be used:85// #!/usr/bin/env zx86```8788```js89// Execa scripts are just regular Node.js files90node file.js91```9293### Global variables9495```js96// zx97await $`echo example`;98```99100```js101// Execa102import {$} from 'execa';103104await $`echo example`;105```106107### Command execution108109```sh110# Bash111echo example112```113114```js115// zx116await $`echo example`;117```118119```js120// Execa121await $`echo example`;122```123

Allow newlines in `$` (#843)ehmickybefore adoption1315486

lines 124–147why, one step back
124### Multiline commands
125126```sh127# Bash128npm run build \129 --example-flag-one \130 --example-flag-two131```132133```js134// zx135await $`npm run build ${[136 '--example-flag-one',137 '--example-flag-two',138]}`;139```140141```js142// Execa143await $`npm run build144 --example-flag-one145 --example-flag-two`146```147

Improve main method documentation (#545)ehmickybefore adoptiondb2ad9a

lines 148–166why, one step back
148### Subcommands
149150```sh151# Bash152echo "$(echo example)"153```154155```js156// zx157const example = await $`echo example`;158await $`echo ${example}`;159```160161```js162// Execa163const example = await $`echo example`;164await $`echo ${example}`;165```166

Fix argument concatenation with `$` (#553)ehmickybefore adoption07585d0

lines 167–186why, one step back
167### Concatenation
168169```sh170# Bash171tmpDir="/tmp"172mkdir "$tmpDir/filename"173```174175```js176// zx177const tmpDir = '/tmp'178await $`mkdir ${tmpDir}/filename`;179```180181```js182// Execa183const tmpDir = '/tmp'184await $`mkdir ${tmpDir}/filename`;185```186

Improve main method documentation (#545)ehmickybefore adoptiondb2ad9a

lines 187–526why, one step back
187### Parallel commands
188189```sh190# Bash191echo one &192echo two &193```194195```js196// zx197await Promise.all([$`echo one`, $`echo two`]);198```199200```js201// Execa202await Promise.all([$`echo one`, $`echo two`]);203```204205### Serial commands206207```sh208# Bash209echo one && echo two210```211212```js213// zx214await $`echo one && echo two`;215```216217```js218// Execa219await $`echo one`;220await $`echo two`;221```222223### Local binaries224225```sh226# Bash227npx tsc --version228```229230```js231// zx232await $`npx tsc --version`;233```234235```js236// Execa237await $`tsc --version`;238```239240### Builtin utilities241242```js243// zx244const content = await stdin();245```246247```js248// Execa249import getStdin from 'get-stdin';250251const content = await getStdin();252```253254### Variable substitution255256```sh257# Bash258echo $LANG259```260261```js262// zx263await $`echo $LANG`;264```265266```js267// Execa268await $`echo ${process.env.LANG}`;269```270271### Environment variables272273```sh274# Bash275EXAMPLE=1 example_command276```277278```js279// zx280$.env.EXAMPLE = '1';281await $`example_command`;282delete $.env.EXAMPLE;283```284285```js286// Execa287await $({env: {EXAMPLE: '1'}})`example_command`;288```289290### Escaping291292```sh293# Bash294echo 'one two'295```296297```js298// zx299await $`echo ${'one two'}`;300```301302```js303// Execa304await $`echo ${'one two'}`;305```306307### Escaping multiple arguments308309```sh310# Bash311echo 'one two' '$'312```313314```js315// zx316await $`echo ${['one two', '$']}`;317```318319```js320// Execa321await $`echo ${['one two', '$']}`;322```323324### Current filename325326```sh327# Bash328echo "$(basename "$0")"329```330331```js332// zx333await $`echo ${__filename}`;334```335336```js337// Execa338import {fileURLToPath} from 'node:url';339import path from 'node:path';340341const __filename = path.basename(fileURLToPath(import.meta.url));342343await $`echo ${__filename}`;344```345346### Verbose mode347348```sh349# Bash350set -v351echo example352```353354```js355// zx >=8356await $`echo example`.verbose();357358// or:359$.verbose = true;360```361362```js363// Execa364const $$ = $({verbose: true});365await $$`echo example`;366```367368Or:369370```371NODE_DEBUG=execa node file.js372```373374### Current directory375376```sh377# Bash378cd project379```380381```js382// zx383cd('project');384385// or:386$.cwd = 'project';387```388389```js390// Execa391const $$ = $({cwd: 'project'});392```393394### Multiple current directories395396```sh397# Bash398pushd project399pwd400popd401pwd402```403404```js405// zx406within(async () => {407 cd('project');408 await $`pwd`;409});410411await $`pwd`;412```413414```js415// Execa416await $({cwd: 'project'})`pwd`;417await $`pwd`;418```419420### Exit codes421422```sh423# Bash424false425echo $?426```427428```js429// zx430const {exitCode} = await $`false`.nothrow();431echo`${exitCode}`;432```433434```js435// Execa436const {exitCode} = await $({reject: false})`false`;437console.log(exitCode);438```439440### Timeouts441442```sh443# Bash444timeout 5 echo example445```446447```js448// zx449await $`echo example`.timeout('5s');450```451452```js453// Execa454await $({timeout: 5000})`echo example`;455```456457### PID458459```sh460# Bash461echo example &462echo $!463```464465```js466// zx does not return `childProcess.pid`467```468469```js470// Execa471const {pid} = $`echo example`;472```473474### Errors475476```sh477# Bash communicates errors only through the exit code and stderr478timeout 1 sleep 2479echo $?480```481482```js483// zx484const {485 stdout,486 stderr,487 exitCode,488 signal,489} = await $`sleep 2`.timeout('1s');490// file:///home/me/Desktop/node_modules/zx/build/core.js:146491// let output = new ProcessOutput(code, signal, stdout, stderr, combined, message);492// ^493// ProcessOutput [Error]:494// at file:///home/me/Desktop/example.js:2:20495// exit code: null496// signal: SIGTERM497// at ChildProcess.<anonymous> (file:///home/me/Desktop/node_modules/zx/build/core.js:146:26)498// at ChildProcess.emit (node:events:512:28)499// at maybeClose (node:internal/child_process:1098:16)500// at Socket.<anonymous> (node:internal/child_process:456:11)501// at Socket.emit (node:events:512:28)502// at Pipe.<anonymous> (node:net:316:12)503// at Pipe.callbackTrampoline (node:internal/async_hooks:130:17) {504// _code: null,505// _signal: 'SIGTERM',506// _stdout: '',507// _stderr: '',508// _combined: ''509// }510```511512```js513// Execa514const {515 stdout,516 stderr,517 exitCode,518 signal,519 signalDescription,520 originalMessage,521 shortMessage,522 command,523 escapedCommand,524 failed,525 timedOut,526 isCanceled,

Fix `error.killed` and rename to `error.isTerminated` (#625)ehmickybefore adoption248349c

line 527why, one step back
527 isTerminated,

Improve main method documentation (#545)ehmickybefore adoptiondb2ad9a

lines 528–547why, one step back
528 // and other error-related properties: code, etc.
529} = await $({timeout: 1})`sleep 2`;530// file:///home/me/code/execa/lib/kill.js:60531// reject(Object.assign(new Error('Timed out'), {timedOut: true, signal}));532// ^533// Error: Command timed out after 1 milliseconds: sleep 2534// Timed out535// at file:///home/me/Desktop/example.js:2:20536// timedOut: true,537// signal: 'SIGTERM',538// originalMessage: 'Timed out',539// shortMessage: 'Command timed out after 1 milliseconds: sleep 2\nTimed out',540// command: 'sleep 2',541// escapedCommand: 'sleep 2',542// exitCode: undefined,543// signalDescription: 'Termination',544// stdout: '',545// stderr: '',546// failed: true,547// isCanceled: false,

Fix `error.killed` and rename to `error.isTerminated` (#625)ehmickybefore adoption248349c

line 548why, one step back
548// isTerminated: false

Improve main method documentation (#545)ehmickybefore adoptiondb2ad9a

lines 549–614why, one step back
549// }
550```551552### Shared options553554```sh555# Bash556options="timeout 5"557$options echo one558$options echo two559$options echo three560```561562```js563// zx564const timeout = '5s';565await $`echo one`.timeout(timeout);566await $`echo two`.timeout(timeout);567await $`echo three`.timeout(timeout);568```569570```js571// Execa572const $$ = $({timeout: 5000});573await $$`echo one`;574await $$`echo two`;575await $$`echo three`;576```577578### Background processes579580```sh581# Bash582echo one &583```584585```js586// zx does not allow setting the `detached` option587```588589```js590// Execa591await $({detached: true})`echo one`;592```593594### Printing to stdout595596```sh597# Bash598echo example599```600601```js602// zx603echo`example`;604```605606```js607// Execa608console.log('example');609```610611### Piping stdout to another command612613```sh614# Bash

Improve piping processes (#834)ehmickybefore adoption1a47ea2

line 615why, one step back
615echo npm run build | sort | head -n2

Improve main method documentation (#545)ehmickybefore adoptiondb2ad9a

lines 616–619why, one step back
616```
617618```js619// zx

Improve piping processes (#834)ehmickybefore adoption1a47ea2

line 620why, one step back
620await $`npm run build | sort | head -n2`;

Improve main method documentation (#545)ehmickybefore adoptiondb2ad9a

lines 621–624why, one step back
621```
622623```js624// Execa

Improve piping processes (#834)ehmickybefore adoption1a47ea2

line 625why, one step back
625await $`npm run build`

`.pipe()` shortcut for `$` (#840)ehmickybefore adoption316f562

lines 626–627why, one step back
626 .pipe`sort`
627 .pipe`head -n2`;

Improve main method documentation (#545)ehmickybefore adoptiondb2ad9a

lines 628–647why, one step back
628```
629630### Piping stdout and stderr to another command631632```sh633# Bash634echo example |& cat635```636637```js638// zx639const echo = $`echo example`;640const cat = $`cat`;641echo.pipe(cat)642echo.stderr.pipe(cat.stdin);643await Promise.all([echo, cat]);644```645646```js647// Execa

`.pipe()` shortcut for `$` (#840)ehmickybefore adoption316f562

lines 648–649why, one step back
648await $({all: true})`echo example`
649 .pipe({from: 'all'})`cat`;

Improve main method documentation (#545)ehmickybefore adoptiondb2ad9a

lines 650–665why, one step back
650```
651652### Piping stdout to a file653654```sh655# Bash656echo example > file.txt657```658659```js660// zx661await $`echo example`.pipe(fs.createWriteStream('file.txt'));662```663664```js665// Execa

Only allow child processes as argument to `.pipeStdout()` (#752)ehmickybefore adoptiond16c305

line 666why, one step back
666await $({stdout: {file: 'file.txt'}})`echo example`;

Improve main method documentation (#545)ehmickybefore adoptiondb2ad9a

lines 667–703why, one step back
667```
668669### Piping stdin from a file670671```sh672# Bash673echo example < file.txt674```675676```js677// zx678const cat = $`cat`679fs.createReadStream('file.txt').pipe(cat.stdin)680await cat681```682683```js684// Execa685await $({inputFile: 'file.txt'})`cat`686```687688### Silent stderr689690```sh691# Bash692echo example 2> /dev/null693```694695```js696// zx697await $`echo example`.stdio('inherit', 'pipe', 'ignore');698```699700```js701// Execa does not forward stdout/stderr by default702await $`echo example`;703```