Skip to content
Myr

scripts.md

This file

Path

docs/scripts.md

676 lines · 11.0 KiB · Markdown

Last changed by

Improve process piping API (#757)ehmickybefore adoption9554a78

History of this file

Take it

Add more documentation for `$` (#533)ehmickybefore adoption9bcfa95

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`

Improve process piping API (#757)ehmickybefore adoption9554a78

line 9why, one step back
9 .pipe($({stdin: 'pipe'})`grep name`);

Add more documentation for `$` (#533)ehmickybefore adoption9bcfa95

lines 10–142why, 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```123124### Subcommands125126```sh127# Bash128echo "$(echo example)"129```130131```js132// zx133const example = await $`echo example`;134await $`echo ${example}`;135```136137```js138// Execa139const example = await $`echo example`;140await $`echo ${example}`;141```142

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

lines 143–162why, one step back
143### Concatenation
144145```sh146# Bash147tmpDir="/tmp"148mkdir "$tmpDir/filename"149```150151```js152// zx153const tmpDir = '/tmp'154await $`mkdir ${tmpDir}/filename`;155```156157```js158// Execa159const tmpDir = '/tmp'160await $`mkdir ${tmpDir}/filename`;161```162

Add more documentation for `$` (#533)ehmickybefore adoption9bcfa95

lines 163–502why, one step back
163### Parallel commands
164165```sh166# Bash167echo one &168echo two &169```170171```js172// zx173await Promise.all([$`echo one`, $`echo two`]);174```175176```js177// Execa178await Promise.all([$`echo one`, $`echo two`]);179```180181### Serial commands182183```sh184# Bash185echo one && echo two186```187188```js189// zx190await $`echo one && echo two`;191```192193```js194// Execa195await $`echo one`;196await $`echo two`;197```198199### Local binaries200201```sh202# Bash203npx tsc --version204```205206```js207// zx208await $`npx tsc --version`;209```210211```js212// Execa213await $`tsc --version`;214```215216### Builtin utilities217218```js219// zx220const content = await stdin();221```222223```js224// Execa225import getStdin from 'get-stdin';226227const content = await getStdin();228```229230### Variable substitution231232```sh233# Bash234echo $LANG235```236237```js238// zx239await $`echo $LANG`;240```241242```js243// Execa244await $`echo ${process.env.LANG}`;245```246247### Environment variables248249```sh250# Bash251EXAMPLE=1 example_command252```253254```js255// zx256$.env.EXAMPLE = '1';257await $`example_command`;258delete $.env.EXAMPLE;259```260261```js262// Execa263await $({env: {EXAMPLE: '1'}})`example_command`;264```265266### Escaping267268```sh269# Bash270echo 'one two'271```272273```js274// zx275await $`echo ${'one two'}`;276```277278```js279// Execa280await $`echo ${'one two'}`;281```282283### Escaping multiple arguments284285```sh286# Bash287echo 'one two' '$'288```289290```js291// zx292await $`echo ${['one two', '$']}`;293```294295```js296// Execa297await $`echo ${['one two', '$']}`;298```299300### Current filename301302```sh303# Bash304echo "$(basename "$0")"305```306307```js308// zx309await $`echo ${__filename}`;310```311312```js313// Execa314import {fileURLToPath} from 'node:url';315import path from 'node:path';316317const __filename = path.basename(fileURLToPath(import.meta.url));318319await $`echo ${__filename}`;320```321322### Verbose mode323324```sh325# Bash326set -v327echo example328```329330```js331// zx >=8332await $`echo example`.verbose();333334// or:335$.verbose = true;336```337338```js339// Execa340const $$ = $({verbose: true});341await $$`echo example`;342```343344Or:345346```347NODE_DEBUG=execa node file.js348```349350### Current directory351352```sh353# Bash354cd project355```356357```js358// zx359cd('project');360361// or:362$.cwd = 'project';363```364365```js366// Execa367const $$ = $({cwd: 'project'});368```369370### Multiple current directories371372```sh373# Bash374pushd project375pwd376popd377pwd378```379380```js381// zx382within(async () => {383 cd('project');384 await $`pwd`;385});386387await $`pwd`;388```389390```js391// Execa392await $({cwd: 'project'})`pwd`;393await $`pwd`;394```395396### Exit codes397398```sh399# Bash400false401echo $?402```403404```js405// zx406const {exitCode} = await $`false`.nothrow();407echo`${exitCode}`;408```409410```js411// Execa412const {exitCode} = await $({reject: false})`false`;413console.log(exitCode);414```415416### Timeouts417418```sh419# Bash420timeout 5 echo example421```422423```js424// zx425await $`echo example`.timeout('5s');426```427428```js429// Execa430await $({timeout: 5000})`echo example`;431```432433### PID434435```sh436# Bash437echo example &438echo $!439```440441```js442// zx does not return `childProcess.pid`443```444445```js446// Execa447const {pid} = $`echo example`;448```449450### Errors451452```sh453# Bash communicates errors only through the exit code and stderr454timeout 1 sleep 2455echo $?456```457458```js459// zx460const {461 stdout,462 stderr,463 exitCode,464 signal,465} = await $`sleep 2`.timeout('1s');466// file:///home/me/Desktop/node_modules/zx/build/core.js:146467// let output = new ProcessOutput(code, signal, stdout, stderr, combined, message);468// ^469// ProcessOutput [Error]:470// at file:///home/me/Desktop/example.js:2:20471// exit code: null472// signal: SIGTERM473// at ChildProcess.<anonymous> (file:///home/me/Desktop/node_modules/zx/build/core.js:146:26)474// at ChildProcess.emit (node:events:512:28)475// at maybeClose (node:internal/child_process:1098:16)476// at Socket.<anonymous> (node:internal/child_process:456:11)477// at Socket.emit (node:events:512:28)478// at Pipe.<anonymous> (node:net:316:12)479// at Pipe.callbackTrampoline (node:internal/async_hooks:130:17) {480// _code: null,481// _signal: 'SIGTERM',482// _stdout: '',483// _stderr: '',484// _combined: ''485// }486```487488```js489// Execa490const {491 stdout,492 stderr,493 exitCode,494 signal,495 signalDescription,496 originalMessage,497 shortMessage,498 command,499 escapedCommand,500 failed,501 timedOut,502 isCanceled,

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

line 503why, one step back
503 isTerminated,

Add more documentation for `$` (#533)ehmickybefore adoption9bcfa95

lines 504–523why, one step back
504 // and other error-related properties: code, etc.
505} = await $({timeout: 1})`sleep 2`;506// file:///home/me/code/execa/lib/kill.js:60507// reject(Object.assign(new Error('Timed out'), {timedOut: true, signal}));508// ^509// Error: Command timed out after 1 milliseconds: sleep 2510// Timed out511// at file:///home/me/Desktop/example.js:2:20512// timedOut: true,513// signal: 'SIGTERM',514// originalMessage: 'Timed out',515// shortMessage: 'Command timed out after 1 milliseconds: sleep 2\nTimed out',516// command: 'sleep 2',517// escapedCommand: 'sleep 2',518// exitCode: undefined,519// signalDescription: 'Termination',520// stdout: '',521// stderr: '',522// failed: true,523// isCanceled: false,

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

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

Add more documentation for `$` (#533)ehmickybefore adoption9bcfa95

lines 525–600why, one step back
525// }
526```527528### Shared options529530```sh531# Bash532options="timeout 5"533$options echo one534$options echo two535$options echo three536```537538```js539// zx540const timeout = '5s';541await $`echo one`.timeout(timeout);542await $`echo two`.timeout(timeout);543await $`echo three`.timeout(timeout);544```545546```js547// Execa548const $$ = $({timeout: 5000});549await $$`echo one`;550await $$`echo two`;551await $$`echo three`;552```553554### Background processes555556```sh557# Bash558echo one &559```560561```js562// zx does not allow setting the `detached` option563```564565```js566// Execa567await $({detached: true})`echo one`;568```569570### Printing to stdout571572```sh573# Bash574echo example575```576577```js578// zx579echo`example`;580```581582```js583// Execa584console.log('example');585```586587### Piping stdout to another command588589```sh590# Bash591echo example | cat592```593594```js595// zx596await $`echo example | cat`;597```598599```js600// Execa

Improve process piping API (#757)ehmickybefore adoption9554a78

line 601why, one step back
601await $`echo example`.pipe($({stdin: 'pipe'})`cat`);

Add more documentation for `$` (#533)ehmickybefore adoption9bcfa95

lines 602–621why, one step back
602```
603604### Piping stdout and stderr to another command605606```sh607# Bash608echo example |& cat609```610611```js612// zx613const echo = $`echo example`;614const cat = $`cat`;615echo.pipe(cat)616echo.stderr.pipe(cat.stdin);617await Promise.all([echo, cat]);618```619620```js621// Execa

Improve process piping API (#757)ehmickybefore adoption9554a78

line 622why, one step back
622await $({all: true})`echo example`.pipe($({stdin: 'pipe'})`cat`, 'all');

Add more documentation for `$` (#533)ehmickybefore adoption9bcfa95

lines 623–638why, one step back
623```
624625### Piping stdout to a file626627```sh628# Bash629echo example > file.txt630```631632```js633// zx634await $`echo example`.pipe(fs.createWriteStream('file.txt'));635```636637```js638// Execa

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

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

Add more documentation for `$` (#533)ehmickybefore adoption9bcfa95

lines 640–657why, one step back
640```
641642### Piping stdin from a file643644```sh645# Bash646echo example < file.txt647```648649```js650// zx651const cat = $`cat`652fs.createReadStream('file.txt').pipe(cat.stdin)653await cat654```655656```js657// Execa

Add `inputFile` option (#542)ehmickybefore adoption0726126

line 658why, one step back
658await $({inputFile: 'file.txt'})`cat`

Add more documentation for `$` (#533)ehmickybefore adoption9bcfa95

lines 659–676why, one step back
659```
660661### Silent stderr662663```sh664# Bash665echo example 2> /dev/null666```667668```js669// zx670await $`echo example`.stdio('inherit', 'pipe', 'ignore');671```672673```js674// Execa does not forward stdout/stderr by default675await $`echo example`;676```