scripts.md
This file
Path
docs/scripts.md
831 lines · 13.8 KiB · Markdown
Last changed by
Make subprocess async iterable (#923)ehmickybefore adoption2e8e8c9
History of this fileTake it
1# Node.js scripts23With 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#cleanup), [interleaved output](#interleaved-output), [forceful termination](../readme.md#forcekillafterdelay), etc.).9 - [easy to debug](#debugging): [verbose mode](#verbose-mode), [detailed errors](#errors), [messages and stack traces](#cancellation), stateless API.1011```js12import {$} from 'execa';1314const {stdout: name} = await $`cat package.json`15 .pipe`grep name`;16console.log(name);1718const branch = await $`git branch --show-current`;19await $`dep deploy --branch=${branch}`;2021await Promise.all([22 $`sleep 1`,23 $`sleep 2`,24 $`sleep 3`,25]);2627const dirName = 'foo bar';28await $`mkdir /tmp/${dirName}`;29```3031## Examples3233### Main binary3435```sh36# Bash37bash file.sh38```3940```js41// zx42zx file.js4344// or a shebang can be used:45// #!/usr/bin/env zx46```4748```js49// Execa scripts are just regular Node.js files50node file.js51```5253### Global variables5455```js56// zx57await $`echo example`;58```5960```js61// Execa62import {$} from 'execa';6364await $`echo example`;65```6667### Command execution6869```sh70# Bash71echo example72```7374```js75// zx76await $`echo example`;77```7879```js80// Execa81await $`echo example`;82```8384### Multiline commands8586```sh87# Bash88npm run build \89 --example-flag-one \90 --example-flag-two91```9293```js94// zx95await $`npm run build ${[96 '--example-flag-one',97 '--example-flag-two',98]}`;99```100101```js102// Execa103await $`npm run build104 --example-flag-one105 --example-flag-two`106```107108### Concatenation109110```sh111# Bash112tmpDir="/tmp"113mkdir "$tmpDir/filename"114```115116```js117// zx118const tmpDir = '/tmp'119await $`mkdir ${tmpDir}/filename`;120```121122```js123// Execa124const tmpDir = '/tmp'125await $`mkdir ${tmpDir}/filename`;126```127128### Variable substitution129130```sh131# Bash132echo $LANG133```134135```js136// zx137await $`echo $LANG`;138```139140```js141// Execa142await $`echo ${process.env.LANG}`;143```144145### Escaping146147```sh148# Bash149echo 'one two'150```151152```js153// zx154await $`echo ${'one two'}`;155```156157```js158// Execa159await $`echo ${'one two'}`;160```161162### Escaping multiple arguments163164```sh165# Bash166echo 'one two' '$'167```168169```js170// zx171await $`echo ${['one two', '$']}`;172```173174```js175// Execa176await $`echo ${['one two', '$']}`;177```178179### Subcommands180181```sh182# Bash183echo "$(echo example)"184```185186```js187// zx188const example = await $`echo example`;189await $`echo ${example}`;190```191192```js193// Execa194const example = await $`echo example`;195await $`echo ${example}`;196```197198### Serial commands199200```sh201# Bash202echo one && echo two203```204205```js206// zx207await $`echo one && echo two`;208```209210```js211// Execa212await $`echo one`;213await $`echo two`;214```215216### Parallel commands217218```sh219# Bash220echo one &221echo two &222```223224```js225// zx226await Promise.all([$`echo one`, $`echo two`]);227```228229```js230// Execa231await Promise.all([$`echo one`, $`echo two`]);232```233234### Global/shared options235236```sh237# Bash238options="timeout 5"239$options echo one240$options echo two241$options echo three242```243244```js245// zx246const timeout = '5s';247await $`echo one`.timeout(timeout);248await $`echo two`.timeout(timeout);249await $`echo three`.timeout(timeout);250```251252```js253// Execa254import {$ as $_} from 'execa';255256const $ = $_({timeout: 5000});257258await $`echo one`;259await $`echo two`;260await $`echo three`;261```262263### Environment variables264265```sh266# Bash267EXAMPLE=1 example_command268```269270```js271// zx272$.env.EXAMPLE = '1';273await $`example_command`;274delete $.env.EXAMPLE;275```276277```js278// Execa279await $({env: {EXAMPLE: '1'}})`example_command`;280```281282### Local binaries283284```sh285# Bash286npx tsc --version287```288289```js290// zx291await $`npx tsc --version`;292```293294```js295// Execa296await $`tsc --version`;297```298299### Builtin utilities300301```js302// zx303const content = await stdin();304```305306```js307// Execa308import getStdin from 'get-stdin';309310const content = await getStdin();311```312313### Printing to stdout314315```sh316# Bash317echo example318```319320```js321// zx322echo`example`;323```324325```js326// Execa327console.log('example');328```329330### Silent stderr331332```sh333# Bash334echo example 2> /dev/null335```336337```js338// zx339await $`echo example`.stdio('inherit', 'pipe', 'ignore');340```341342```js343// Execa does not print stdout/stderr by default344await $`echo example`;345```346347### Verbose mode348349```sh350# Bash351set -v352echo example353```354355```js356// zx >=8357await $`echo example`.verbose();358359// or:360$.verbose = true;361```362363```js364// Execa365import {$ as $_} from 'execa';366367// `verbose: 'short'` is also available368const $ = $_({verbose: 'full'});369370await $`echo example`;371```372373Or:374375```376NODE_DEBUG=execa node file.js377```378379Which prints:380381```382[19:49:00.360] [0] $ echo example383example384[19:49:00.383] [0] √ (done in 23ms)385```386387### Piping stdout to another command388389```sh390# Bash391echo npm run build | sort | head -n2392```393394```js395// zx396await $`npm run build | sort | head -n2`;397```398399```js400// Execa401await $`npm run build`402 .pipe`sort`403 .pipe`head -n2`;404```405406### Piping stdout and stderr to another command407408```sh409# Bash410echo example |& cat411```412413```js414// zx415const echo = $`echo example`;416const cat = $`cat`;417echo.pipe(cat)418echo.stderr.pipe(cat.stdin);419await Promise.all([echo, cat]);420```421422```js423// Execa424await $({all: true})`echo example`425 .pipe({from: 'all'})`cat`;426```427428### Piping stdout to a file429430```sh431# Bash432echo example > file.txt433```434435```js436// zx437await $`echo example`.pipe(fs.createWriteStream('file.txt'));438```439440```js441// Execa442await $({stdout: {file: 'file.txt'}})`echo example`;443```444445### Piping stdin from a file446447```sh448# Bash449echo example < file.txt450```451452```js453// zx454const cat = $`cat`455fs.createReadStream('file.txt').pipe(cat.stdin)456await cat457```458459```js460// Execa461await $({inputFile: 'file.txt'})`cat`462```463464### Iterate over output lines465466```sh467# Bash468while read469do470 if [[ "$REPLY" == *ERROR* ]]471 then472 echo "$REPLY"473 fi474done < <(npm run build)475```476477```js478// zx does not allow proper iteration.479// For example, the iteration does not handle subprocess errors.480```481482```js483// Execa484for await (const line of $`npm run build`) {485 if (line.includes('ERROR')) {486 console.log(line);487 }488}489```490491### Errors492493```sh494# Bash communicates errors only through the exit code and stderr495timeout 1 sleep 2496echo $?497```498499```js500// zx501const {502 stdout,503 stderr,504 exitCode,505 signal,506} = await $`sleep 2`.timeout('1s');507// file:///home/me/Desktop/node_modules/zx/build/core.js:146508// let output = new ProcessOutput(code, signal, stdout, stderr, combined, message);509// ^510// ProcessOutput [Error]:511// at file:///home/me/Desktop/example.js:2:20512// exit code: null513// signal: SIGTERM514// at ChildProcess.<anonymous> (file:///home/me/Desktop/node_modules/zx/build/core.js:146:26)515// at ChildProcess.emit (node:events:512:28)516// at maybeClose (node:internal/child_process:1098:16)517// at Socket.<anonymous> (node:internal/child_process:456:11)518// at Socket.emit (node:events:512:28)519// at Pipe.<anonymous> (node:net:316:12)520// at Pipe.callbackTrampoline (node:internal/async_hooks:130:17) {521// _code: null,522// _signal: 'SIGTERM',523// _stdout: '',524// _stderr: '',525// _combined: ''526// }527```528529```js530// Execa531const {532 stdout,533 stderr,534 exitCode,535 signal,536 signalDescription,537 originalMessage,538 shortMessage,539 command,540 escapedCommand,541 failed,542 timedOut,543 isCanceled,544 isTerminated,545 // and other error-related properties: code, etc.546} = await $({timeout: 1})`sleep 2`;547// ExecaError: Command timed out after 1 milliseconds: sleep 2548// at file:///home/me/Desktop/example.js:2:20549// at ... {550// shortMessage: 'Command timed out after 1 milliseconds: sleep 2\nTimed out',551// originalMessage: '',552// command: 'sleep 2',553// escapedCommand: 'sleep 2',554// cwd: '/path/to/cwd',555// durationMs: 19.95693,556// failed: true,557// timedOut: true,558// isCanceled: false,559// isTerminated: true,560// signal: 'SIGTERM',561// signalDescription: 'Termination',562// stdout: '',563// stderr: '',564// stdio: [undefined, '', ''],565// pipedFrom: []566// }567```568569### Exit codes570571```sh572# Bash573false574echo $?575```576577```js578// zx579const {exitCode} = await $`false`.nothrow();580echo`${exitCode}`;581```582583```js584// Execa585const {exitCode} = await $({reject: false})`false`;586console.log(exitCode);587```588589### Timeouts590591```sh592# Bash593timeout 5 echo example594```595596```js597// zx598await $`echo example`.timeout('5s');599```600601```js602// Execa603await $({timeout: 5000})`echo example`;604```605606### Current filename607608```sh609# Bash610echo "$(basename "$0")"611```612613```js614// zx615await $`echo ${__filename}`;616```617618```js619// Execa620import {fileURLToPath} from 'node:url';621import path from 'node:path';622623const __filename = path.basename(fileURLToPath(import.meta.url));624625await $`echo ${__filename}`;626```627628### Current directory629630```sh631# Bash632cd project633```634635```js636// zx637cd('project');638639// or:640$.cwd = 'project';641```642643```js644// Execa645const $$ = $({cwd: 'project'});646```647648### Multiple current directories649650```sh651# Bash652pushd project653pwd654popd655pwd656```657658```js659// zx660within(async () => {661 cd('project');662 await $`pwd`;663});664665await $`pwd`;666```667668```js669// Execa670await $({cwd: 'project'})`pwd`;671await $`pwd`;672```673674### Background subprocesses675676```sh677# Bash678echo one &679```680681```js682// zx does not allow setting the `detached` option683```684685```js686// Execa687await $({detached: true})`echo one`;688```689690### IPC691692```sh693# Bash does not allow simple IPC694```695696```js697// zx does not allow simple IPC698```699700```js701// Execa702const subprocess = $({ipc: true})`node script.js`;703704subprocess.on('message', message => {705 if (message === 'ping') {706 subprocess.send('pong');707 }708});709```710711### Transforms712713```sh714# Bash does not allow transforms715```716717```js718// zx does not allow transforms719```720721```js722// Execa723const transform = function * (line) {724 if (!line.includes('secret')) {725 yield line;726 }727};728729await $({stdout: [transform, 'inherit']})`echo ${'This is a secret.'}`;730```731732### Cancellation733734```sh735# Bash736kill $PID737```738739```js740// zx741subprocess.kill();742```743744```js745// Execa746// Can specify an error message and stack trace747subprocess.kill(error);748749// Or use an `AbortSignal`750const controller = new AbortController();751await $({signal: controller.signal})`node long-script.js`;752```753754### Interleaved output755756```sh757# Bash prints stdout and stderr interleaved758```759760```js761// zx separates stdout and stderr762const {stdout, stderr} = await $`node example.js`;763```764765```js766// Execa can interleave stdout and stderr767const {all} = await $({all: true})`node example.js`;768```769770### PID771772```sh773# Bash774echo example &775echo $!776```777778```js779// zx does not return `subprocess.pid`780```781782```js783// Execa784const {pid} = $`echo example`;785```786787## Differences with Bash and zx788789This section describes the differences between Bash, Execa, and [zx](https://github.com/google/zx) (which inspired this feature).790791### Flexibility792793Unlike 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).794795### Shell796797The 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.798799This is more cross-platform. For example, your code works the same on Windows machines without Bash installed.800801Also, there is no shell syntax to remember: everything is just plain JavaScript.802803If you really need a shell though, the [`shell` option](../readme.md#shell) can be used.804805### Simplicity806807Execa's scripting API mostly consists of only two methods: [`` $`command` ``](../readme.md#command) and [`$(options)`](../readme.md#options).808809[No special binary](#main-binary) is recommended, no [global variable](#global-variables) is injected: scripts are regular Node.js files.810811Execa 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](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), [`cancelSignal`](https://nodejs.org/api/child_process.html#child_processspawncommand-args-options), etc.812813### Modularity814815zx includes many builtin utilities: `fetch()`, `question()`, `sleep()`, `stdin()`, `retry()`, `spinner()`, `chalk`, `fs-extra`, `os`, `path`, `globby`, `yaml`, `minimist`, `which`, Markdown scripts, remote scripts.816817Execa 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.818819### Performance820821Spawning a shell for every command comes at a performance cost, which Execa avoids.822823Also, [local binaries](#local-binaries) can be directly executed without using `npx`.824825### Debugging826827Subprocesses can be hard to debug, which is why Execa includes a [`verbose` option](#verbose-mode).828829Also, 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#killerror).830831Finally, unlike Bash and zx, which are stateful (options, current directory, etc.), Execa is [purely functional](#current-directory), which also helps with debugging.