scripts.md
This file
Path
docs/scripts.md
679 lines · 11.0 KiB · Markdown
Last changed by
`.pipe()` shortcut for `$` (#840)ehmickybefore adoption316f562
History of this fileTake 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 back1# Node.js scripts23With 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 back9 .pipe`grep name`;Improve main method documentation (#545)ehmickybefore adoptiondb2ad9a
lines 10–142why, one step back10console.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```142Fix argument concatenation with `$` (#553)ehmickybefore adoption07585d0
lines 143–162why, one step back143### Concatenation144145```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```162Improve main method documentation (#545)ehmickybefore adoptiondb2ad9a
lines 163–502why, one step back163### Parallel commands164165```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 back503 isTerminated,Improve main method documentation (#545)ehmickybefore adoptiondb2ad9a
lines 504–523why, one step back504 // 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 back524// isTerminated: falseImprove main method documentation (#545)ehmickybefore adoptiondb2ad9a
lines 525–590why, one step back525// }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# BashImprove piping processes (#834)ehmickybefore adoption1a47ea2
line 591why, one step back591echo npm run build | sort | head -n2Improve main method documentation (#545)ehmickybefore adoptiondb2ad9a
lines 592–595why, one step back592```593594```js595// zxImprove piping processes (#834)ehmickybefore adoption1a47ea2
line 596why, one step back596await $`npm run build | sort | head -n2`;Improve main method documentation (#545)ehmickybefore adoptiondb2ad9a
lines 597–600why, one step back597```598599```js600// ExecaImprove piping processes (#834)ehmickybefore adoption1a47ea2
line 601why, one step back601await $`npm run build``.pipe()` shortcut for `$` (#840)ehmickybefore adoption316f562
lines 602–603why, one step back602 .pipe`sort`603 .pipe`head -n2`;Improve main method documentation (#545)ehmickybefore adoptiondb2ad9a
lines 604–623why, one step back604```605606### Piping stdout and stderr to another command607608```sh609# Bash610echo example |& cat611```612613```js614// zx615const echo = $`echo example`;616const cat = $`cat`;617echo.pipe(cat)618echo.stderr.pipe(cat.stdin);619await Promise.all([echo, cat]);620```621622```js623// Execa`.pipe()` shortcut for `$` (#840)ehmickybefore adoption316f562
lines 624–625why, one step back624await $({all: true})`echo example`625 .pipe({from: 'all'})`cat`;Improve main method documentation (#545)ehmickybefore adoptiondb2ad9a
lines 626–641why, one step back626```627628### Piping stdout to a file629630```sh631# Bash632echo example > file.txt633```634635```js636// zx637await $`echo example`.pipe(fs.createWriteStream('file.txt'));638```639640```js641// ExecaOnly allow child processes as argument to `.pipeStdout()` (#752)ehmickybefore adoptiond16c305
line 642why, one step back642await $({stdout: {file: 'file.txt'}})`echo example`;Improve main method documentation (#545)ehmickybefore adoptiondb2ad9a
lines 643–679why, one step back643```644645### Piping stdin from a file646647```sh648# Bash649echo example < file.txt650```651652```js653// zx654const cat = $`cat`655fs.createReadStream('file.txt').pipe(cat.stdin)656await cat657```658659```js660// Execa661await $({inputFile: 'file.txt'})`cat`662```663664### Silent stderr665666```sh667# Bash668echo example 2> /dev/null669```670671```js672// zx673await $`echo example`.stdio('inherit', 'pipe', 'ignore');674```675676```js677// Execa does not forward stdout/stderr by default678await $`echo example`;679```