scripts.md
This file
Path
docs/scripts.md
709 lines · 11.3 KiB · Markdown
Last changed by
Improve documentation of global script options (#870)ehmickybefore adoption146fa07
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–123why, 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```123Allow newlines in `$` (#843)ehmickybefore adoption1315486
lines 124–147why, one step back124### Multiline commands125126```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```147Improve main method documentation (#545)ehmickybefore adoptiondb2ad9a
lines 148–166why, one step back148### Subcommands149150```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```166Fix argument concatenation with `$` (#553)ehmickybefore adoption07585d0
lines 167–186why, one step back167### Concatenation168169```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```186Improve main method documentation (#545)ehmickybefore adoptiondb2ad9a
lines 187–363why, one step back187### Parallel commands188189```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// ExecaImprove documentation of global script options (#870)ehmickybefore adoption146fa07
lines 364–368why, one step back364import {$ as $_} from 'execa';365366const $ = $_({verbose: true});367368await $`echo example`;Improve main method documentation (#545)ehmickybefore adoptiondb2ad9a
lines 369–529why, one step back369```370371Or:372373```374NODE_DEBUG=execa node file.js375```376377### Current directory378379```sh380# Bash381cd project382```383384```js385// zx386cd('project');387388// or:389$.cwd = 'project';390```391392```js393// Execa394const $$ = $({cwd: 'project'});395```396397### Multiple current directories398399```sh400# Bash401pushd project402pwd403popd404pwd405```406407```js408// zx409within(async () => {410 cd('project');411 await $`pwd`;412});413414await $`pwd`;415```416417```js418// Execa419await $({cwd: 'project'})`pwd`;420await $`pwd`;421```422423### Exit codes424425```sh426# Bash427false428echo $?429```430431```js432// zx433const {exitCode} = await $`false`.nothrow();434echo`${exitCode}`;435```436437```js438// Execa439const {exitCode} = await $({reject: false})`false`;440console.log(exitCode);441```442443### Timeouts444445```sh446# Bash447timeout 5 echo example448```449450```js451// zx452await $`echo example`.timeout('5s');453```454455```js456// Execa457await $({timeout: 5000})`echo example`;458```459460### PID461462```sh463# Bash464echo example &465echo $!466```467468```js469// zx does not return `childProcess.pid`470```471472```js473// Execa474const {pid} = $`echo example`;475```476477### Errors478479```sh480# Bash communicates errors only through the exit code and stderr481timeout 1 sleep 2482echo $?483```484485```js486// zx487const {488 stdout,489 stderr,490 exitCode,491 signal,492} = await $`sleep 2`.timeout('1s');493// file:///home/me/Desktop/node_modules/zx/build/core.js:146494// let output = new ProcessOutput(code, signal, stdout, stderr, combined, message);495// ^496// ProcessOutput [Error]:497// at file:///home/me/Desktop/example.js:2:20498// exit code: null499// signal: SIGTERM500// at ChildProcess.<anonymous> (file:///home/me/Desktop/node_modules/zx/build/core.js:146:26)501// at ChildProcess.emit (node:events:512:28)502// at maybeClose (node:internal/child_process:1098:16)503// at Socket.<anonymous> (node:internal/child_process:456:11)504// at Socket.emit (node:events:512:28)505// at Pipe.<anonymous> (node:net:316:12)506// at Pipe.callbackTrampoline (node:internal/async_hooks:130:17) {507// _code: null,508// _signal: 'SIGTERM',509// _stdout: '',510// _stderr: '',511// _combined: ''512// }513```514515```js516// Execa517const {518 stdout,519 stderr,520 exitCode,521 signal,522 signalDescription,523 originalMessage,524 shortMessage,525 command,526 escapedCommand,527 failed,528 timedOut,529 isCanceled,Fix `error.killed` and rename to `error.isTerminated` (#625)ehmickybefore adoption248349c
line 530why, one step back530 isTerminated,Improve main method documentation (#545)ehmickybefore adoptiondb2ad9a
lines 531–550why, one step back531 // and other error-related properties: code, etc.532} = await $({timeout: 1})`sleep 2`;533// file:///home/me/code/execa/lib/kill.js:60534// reject(Object.assign(new Error('Timed out'), {timedOut: true, signal}));535// ^536// Error: Command timed out after 1 milliseconds: sleep 2537// Timed out538// at file:///home/me/Desktop/example.js:2:20539// timedOut: true,540// signal: 'SIGTERM',541// originalMessage: 'Timed out',542// shortMessage: 'Command timed out after 1 milliseconds: sleep 2\nTimed out',543// command: 'sleep 2',544// escapedCommand: 'sleep 2',545// exitCode: undefined,546// signalDescription: 'Termination',547// stdout: '',548// stderr: '',549// failed: true,550// isCanceled: false,Fix `error.killed` and rename to `error.isTerminated` (#625)ehmickybefore adoption248349c
line 551why, one step back551// isTerminated: falseImprove main method documentation (#545)ehmickybefore adoptiondb2ad9a
lines 552–554why, one step back552// }553```554Improve documentation of global script options (#870)ehmickybefore adoption146fa07
line 555why, one step back555### Global/shared optionsImprove main method documentation (#545)ehmickybefore adoptiondb2ad9a
lines 556–574why, one step back556557```sh558# Bash559options="timeout 5"560$options echo one561$options echo two562$options echo three563```564565```js566// zx567const timeout = '5s';568await $`echo one`.timeout(timeout);569await $`echo two`.timeout(timeout);570await $`echo three`.timeout(timeout);571```572573```js574// ExecaImprove documentation of global script options (#870)ehmickybefore adoption146fa07
lines 575–581why, one step back575import {$ as $_} from 'execa';576577const $ = $_({timeout: 5000});578579await $`echo one`;580await $`echo two`;581await $`echo three`;Improve main method documentation (#545)ehmickybefore adoptiondb2ad9a
lines 582–620why, one step back582```583584### Background processes585586```sh587# Bash588echo one &589```590591```js592// zx does not allow setting the `detached` option593```594595```js596// Execa597await $({detached: true})`echo one`;598```599600### Printing to stdout601602```sh603# Bash604echo example605```606607```js608// zx609echo`example`;610```611612```js613// Execa614console.log('example');615```616617### Piping stdout to another command618619```sh620# BashImprove piping processes (#834)ehmickybefore adoption1a47ea2
line 621why, one step back621echo npm run build | sort | head -n2Improve main method documentation (#545)ehmickybefore adoptiondb2ad9a
lines 622–625why, one step back622```623624```js625// zxImprove piping processes (#834)ehmickybefore adoption1a47ea2
line 626why, one step back626await $`npm run build | sort | head -n2`;Improve main method documentation (#545)ehmickybefore adoptiondb2ad9a
lines 627–630why, one step back627```628629```js630// ExecaImprove piping processes (#834)ehmickybefore adoption1a47ea2
line 631why, one step back631await $`npm run build``.pipe()` shortcut for `$` (#840)ehmickybefore adoption316f562
lines 632–633why, one step back632 .pipe`sort`633 .pipe`head -n2`;Improve main method documentation (#545)ehmickybefore adoptiondb2ad9a
lines 634–653why, one step back634```635636### Piping stdout and stderr to another command637638```sh639# Bash640echo example |& cat641```642643```js644// zx645const echo = $`echo example`;646const cat = $`cat`;647echo.pipe(cat)648echo.stderr.pipe(cat.stdin);649await Promise.all([echo, cat]);650```651652```js653// Execa`.pipe()` shortcut for `$` (#840)ehmickybefore adoption316f562
lines 654–655why, one step back654await $({all: true})`echo example`655 .pipe({from: 'all'})`cat`;Improve main method documentation (#545)ehmickybefore adoptiondb2ad9a
lines 656–671why, one step back656```657658### Piping stdout to a file659660```sh661# Bash662echo example > file.txt663```664665```js666// zx667await $`echo example`.pipe(fs.createWriteStream('file.txt'));668```669670```js671// ExecaOnly allow child processes as argument to `.pipeStdout()` (#752)ehmickybefore adoptiond16c305
line 672why, one step back672await $({stdout: {file: 'file.txt'}})`echo example`;Improve main method documentation (#545)ehmickybefore adoptiondb2ad9a
lines 673–709why, one step back673```674675### Piping stdin from a file676677```sh678# Bash679echo example < file.txt680```681682```js683// zx684const cat = $`cat`685fs.createReadStream('file.txt').pipe(cat.stdin)686await cat687```688689```js690// Execa691await $({inputFile: 'file.txt'})`cat`692```693694### Silent stderr695696```sh697# Bash698echo example 2> /dev/null699```700701```js702// zx703await $`echo example`.stdio('inherit', 'pipe', 'ignore');704```705706```js707// Execa does not forward stdout/stderr by default708await $`echo example`;709```