Skip to content
Myr

scripts.md

This file

Path

docs/scripts.md

846 lines · 14.6 KiB · Markdown

Last changed by

Allow template strings with all methods (#933)ehmickybefore adoption8074d85

History of this file

Take it

Show it rendered

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## Template string syntax3233The examples below use the [template string syntax](../readme.md#template-string-syntax). However, the other syntax using [an array of arguments](../readme.md#execafile-arguments-options) is also available as `$(file, arguments?, options?)`.3435Also, the template string syntax can be used outside of script files: `$` is not required to use that syntax. For example, `execa` can use it too.3637The only difference between `$` and `execa` is that the former includes [script-friendly default options](../readme.md#file-arguments-options).3839```js40import {execa, $} from 'execa';4142const branch = await execa`git branch --show-current`;43await $('dep', ['deploy', `--branch=${branch}`]);44```4546## Examples4748### Main binary4950```sh51# Bash52bash file.sh53```5455```js56// zx57zx file.js5859// or a shebang can be used:60//   #!/usr/bin/env zx61```6263```js64// Execa scripts are just regular Node.js files65node file.js66```6768### Global variables6970```js71// zx72await $`echo example`;73```7475```js76// Execa77import {$} from 'execa';7879await $`echo example`;80```8182### Command execution8384```sh85# Bash86echo example87```8889```js90// zx91await $`echo example`;92```9394```js95// Execa96await $`echo example`;97```9899### Multiline commands100101```sh102# Bash103npm run build \104  --example-flag-one \105  --example-flag-two106```107108```js109// zx110await $`npm run build ${[111	'--example-flag-one',112	'--example-flag-two',113]}`;114```115116```js117// Execa118await $`npm run build119	--example-flag-one120	--example-flag-two`121```122123### Concatenation124125```sh126# Bash127tmpDir="/tmp"128mkdir "$tmpDir/filename"129```130131```js132// zx133const tmpDir = '/tmp'134await $`mkdir ${tmpDir}/filename`;135```136137```js138// Execa139const tmpDir = '/tmp'140await $`mkdir ${tmpDir}/filename`;141```142143### Variable substitution144145```sh146# Bash147echo $LANG148```149150```js151// zx152await $`echo $LANG`;153```154155```js156// Execa157await $`echo ${process.env.LANG}`;158```159160### Escaping161162```sh163# Bash164echo 'one two'165```166167```js168// zx169await $`echo ${'one two'}`;170```171172```js173// Execa174await $`echo ${'one two'}`;175```176177### Escaping multiple arguments178179```sh180# Bash181echo 'one two' '$'182```183184```js185// zx186await $`echo ${['one two', '$']}`;187```188189```js190// Execa191await $`echo ${['one two', '$']}`;192```193194### Subcommands195196```sh197# Bash198echo "$(echo example)"199```200201```js202// zx203const example = await $`echo example`;204await $`echo ${example}`;205```206207```js208// Execa209const example = await $`echo example`;210await $`echo ${example}`;211```212213### Serial commands214215```sh216# Bash217echo one && echo two218```219220```js221// zx222await $`echo one && echo two`;223```224225```js226// Execa227await $`echo one`;228await $`echo two`;229```230231### Parallel commands232233```sh234# Bash235echo one &236echo two &237```238239```js240// zx241await Promise.all([$`echo one`, $`echo two`]);242```243244```js245// Execa246await Promise.all([$`echo one`, $`echo two`]);247```248249### Global/shared options250251```sh252# Bash253options="timeout 5"254$options echo one255$options echo two256$options echo three257```258259```js260// zx261const timeout = '5s';262await $`echo one`.timeout(timeout);263await $`echo two`.timeout(timeout);264await $`echo three`.timeout(timeout);265```266267```js268// Execa269import {$ as $_} from 'execa';270271const $ = $_({timeout: 5000});272273await $`echo one`;274await $`echo two`;275await $`echo three`;276```277278### Environment variables279280```sh281# Bash282EXAMPLE=1 example_command283```284285```js286// zx287$.env.EXAMPLE = '1';288await $`example_command`;289delete $.env.EXAMPLE;290```291292```js293// Execa294await $({env: {EXAMPLE: '1'}})`example_command`;295```296297### Local binaries298299```sh300# Bash301npx tsc --version302```303304```js305// zx306await $`npx tsc --version`;307```308309```js310// Execa311await $`tsc --version`;312```313314### Builtin utilities315316```js317// zx318const content = await stdin();319```320321```js322// Execa323import getStdin from 'get-stdin';324325const content = await getStdin();326```327328### Printing to stdout329330```sh331# Bash332echo example333```334335```js336// zx337echo`example`;338```339340```js341// Execa342console.log('example');343```344345### Silent stderr346347```sh348# Bash349echo example 2> /dev/null350```351352```js353// zx354await $`echo example`.stdio('inherit', 'pipe', 'ignore');355```356357```js358// Execa does not print stdout/stderr by default359await $`echo example`;360```361362### Verbose mode363364```sh365# Bash366set -v367echo example368```369370```js371// zx >=8372await $`echo example`.verbose();373374// or:375$.verbose = true;376```377378```js379// Execa380import {$ as $_} from 'execa';381382// `verbose: 'short'` is also available383const $ = $_({verbose: 'full'});384385await $`echo example`;386```387388Or:389390```391NODE_DEBUG=execa node file.js392```393394Which prints:395396```397[19:49:00.360] [0] $ echo example398example399[19:49:00.383] [0] √ (done in 23ms)400```401402### Piping stdout to another command403404```sh405# Bash406echo npm run build | sort | head -n2407```408409```js410// zx411await $`npm run build | sort | head -n2`;412```413414```js415// Execa416await $`npm run build`417	.pipe`sort`418	.pipe`head -n2`;419```420421### Piping stdout and stderr to another command422423```sh424# Bash425echo example |& cat426```427428```js429// zx430const echo = $`echo example`;431const cat = $`cat`;432echo.pipe(cat)433echo.stderr.pipe(cat.stdin);434await Promise.all([echo, cat]);435```436437```js438// Execa439await $({all: true})`echo example`440	.pipe({from: 'all'})`cat`;441```442443### Piping stdout to a file444445```sh446# Bash447echo example > file.txt448```449450```js451// zx452await $`echo example`.pipe(fs.createWriteStream('file.txt'));453```454455```js456// Execa457await $({stdout: {file: 'file.txt'}})`echo example`;458```459460### Piping stdin from a file461462```sh463# Bash464echo example < file.txt465```466467```js468// zx469const cat = $`cat`470fs.createReadStream('file.txt').pipe(cat.stdin)471await cat472```473474```js475// Execa476await $({inputFile: 'file.txt'})`cat`477```478479### Iterate over output lines480481```sh482# Bash483while read484do485	if [[ "$REPLY" == *ERROR* ]]486	then487		echo "$REPLY"488	fi489done < <(npm run build)490```491492```js493// zx does not allow proper iteration.494// For example, the iteration does not handle subprocess errors.495```496497```js498// Execa499for await (const line of $`npm run build`) {500	if (line.includes('ERROR')) {501		console.log(line);502	}503}504```505506### Errors507508```sh509# Bash communicates errors only through the exit code and stderr510timeout 1 sleep 2511echo $?512```513514```js515// zx516const {517	stdout,518	stderr,519	exitCode,520	signal,521} = await $`sleep 2`.timeout('1s');522// file:///home/me/Desktop/node_modules/zx/build/core.js:146523//             let output = new ProcessOutput(code, signal, stdout, stderr, combined, message);524//                          ^525// ProcessOutput [Error]:526//     at file:///home/me/Desktop/example.js:2:20527//     exit code: null528//     signal: SIGTERM529//     at ChildProcess.<anonymous> (file:///home/me/Desktop/node_modules/zx/build/core.js:146:26)530//     at ChildProcess.emit (node:events:512:28)531//     at maybeClose (node:internal/child_process:1098:16)532//     at Socket.<anonymous> (node:internal/child_process:456:11)533//     at Socket.emit (node:events:512:28)534//     at Pipe.<anonymous> (node:net:316:12)535//     at Pipe.callbackTrampoline (node:internal/async_hooks:130:17) {536//   _code: null,537//   _signal: 'SIGTERM',538//   _stdout: '',539//   _stderr: '',540//   _combined: ''541// }542```543544```js545// Execa546const {547  stdout,548  stderr,549  exitCode,550  signal,551  signalDescription,552  originalMessage,553  shortMessage,554  command,555  escapedCommand,556  failed,557  timedOut,558  isCanceled,559  isTerminated,560	// and other error-related properties: code, etc.561} = await $({timeout: 1})`sleep 2`;562// ExecaError: Command timed out after 1 milliseconds: sleep 2563//     at file:///home/me/Desktop/example.js:2:20564//     at ... {565//   shortMessage: 'Command timed out after 1 milliseconds: sleep 2\nTimed out',566//   originalMessage: '',567//   command: 'sleep 2',568//   escapedCommand: 'sleep 2',569//   cwd: '/path/to/cwd',570//   durationMs: 19.95693,571//   failed: true,572//   timedOut: true,573//   isCanceled: false,574//   isTerminated: true,575//   signal: 'SIGTERM',576//   signalDescription: 'Termination',577//   stdout: '',578//   stderr: '',579//   stdio: [undefined, '', ''],580//   pipedFrom: []581// }582```583584### Exit codes585586```sh587# Bash588false589echo $?590```591592```js593// zx594const {exitCode} = await $`false`.nothrow();595echo`${exitCode}`;596```597598```js599// Execa600const {exitCode} = await $({reject: false})`false`;601console.log(exitCode);602```603604### Timeouts605606```sh607# Bash608timeout 5 echo example609```610611```js612// zx613await $`echo example`.timeout('5s');614```615616```js617// Execa618await $({timeout: 5000})`echo example`;619```620621### Current filename622623```sh624# Bash625echo "$(basename "$0")"626```627628```js629// zx630await $`echo ${__filename}`;631```632633```js634// Execa635import {fileURLToPath} from 'node:url';636import path from 'node:path';637638const __filename = path.basename(fileURLToPath(import.meta.url));639640await $`echo ${__filename}`;641```642643### Current directory644645```sh646# Bash647cd project648```649650```js651// zx652cd('project');653654// or:655$.cwd = 'project';656```657658```js659// Execa660const $$ = $({cwd: 'project'});661```662663### Multiple current directories664665```sh666# Bash667pushd project668pwd669popd670pwd671```672673```js674// zx675within(async () => {676	cd('project');677	await $`pwd`;678});679680await $`pwd`;681```682683```js684// Execa685await $({cwd: 'project'})`pwd`;686await $`pwd`;687```688689### Background subprocesses690691```sh692# Bash693echo one &694```695696```js697// zx does not allow setting the `detached` option698```699700```js701// Execa702await $({detached: true})`echo one`;703```704705### IPC706707```sh708# Bash does not allow simple IPC709```710711```js712// zx does not allow simple IPC713```714715```js716// Execa717const subprocess = $({ipc: true})`node script.js`;718719subprocess.on('message', message => {720	if (message === 'ping') {721		subprocess.send('pong');722	}723});724```725726### Transforms727728```sh729# Bash does not allow transforms730```731732```js733// zx does not allow transforms734```735736```js737// Execa738const transform = function * (line) {739	if (!line.includes('secret')) {740		yield line;741	}742};743744await $({stdout: [transform, 'inherit']})`echo ${'This is a secret.'}`;745```746747### Cancellation748749```sh750# Bash751kill $PID752```753754```js755// zx756subprocess.kill();757```758759```js760// Execa761// Can specify an error message and stack trace762subprocess.kill(error);763764// Or use an `AbortSignal`765const controller = new AbortController();766await $({signal: controller.signal})`node long-script.js`;767```768769### Interleaved output770771```sh772# Bash prints stdout and stderr interleaved773```774775```js776// zx separates stdout and stderr777const {stdout, stderr} = await $`node example.js`;778```779780```js781// Execa can interleave stdout and stderr782const {all} = await $({all: true})`node example.js`;783```784785### PID786787```sh788# Bash789echo example &790echo $!791```792793```js794// zx does not return `subprocess.pid`795```796797```js798// Execa799const {pid} = $`echo example`;800```801802## Differences with Bash and zx803804This section describes the differences between Bash, Execa, and [zx](https://github.com/google/zx) (which inspired this feature).805806### Flexibility807808Unlike 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).809810### Shell811812The 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.813814This is more cross-platform. For example, your code works the same on Windows machines without Bash installed.815816Also, there is no shell syntax to remember: everything is just plain JavaScript.817818If you really need a shell though, the [`shell` option](../readme.md#shell) can be used.819820### Simplicity821822Execa's scripting API mostly consists of only two methods: [`` $`command` ``](../readme.md#file-arguments-options) and [`$(options)`](../readme.md#execaoptions).823824[No special binary](#main-binary) is recommended, no [global variable](#global-variables) is injected: scripts are regular Node.js files.825826Execa 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.827828### Modularity829830zx includes many builtin utilities: `fetch()`, `question()`, `sleep()`, `stdin()`, `retry()`, `spinner()`, `chalk`, `fs-extra`, `os`, `path`, `globby`, `yaml`, `minimist`, `which`, Markdown scripts, remote scripts.831832Execa 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.833834### Performance835836Spawning a shell for every command comes at a performance cost, which Execa avoids.837838Also, [local binaries](#local-binaries) can be directly executed without using `npx`.839840### Debugging841842Subprocesses can be hard to debug, which is why Execa includes a [`verbose` option](#verbose-mode).843844Also, 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).845846Finally, unlike Bash and zx, which are stateful (options, current directory, etc.), Execa is [purely functional](#current-directory), which also helps with debugging.