Skip to content
Myr

scripts.md

This file

Path

docs/scripts.md

656 lines · 10.7 KiB · Markdown

Last changed by

Fix documentation about piping from stdin (#536)ehmickybefore adoption4857cc4

History of this file

Take it

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

lines 1–637why, 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`9 .pipeStdout($`grep name`);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```142143### Parallel commands144145```sh146# Bash147echo one &148echo two &149```150151```js152// zx153await Promise.all([$`echo one`, $`echo two`]);154```155156```js157// Execa158await Promise.all([$`echo one`, $`echo two`]);159```160161### Serial commands162163```sh164# Bash165echo one && echo two166```167168```js169// zx170await $`echo one && echo two`;171```172173```js174// Execa175await $`echo one`;176await $`echo two`;177```178179### Local binaries180181```sh182# Bash183npx tsc --version184```185186```js187// zx188await $`npx tsc --version`;189```190191```js192// Execa193await $`tsc --version`;194```195196### Builtin utilities197198```js199// zx200const content = await stdin();201```202203```js204// Execa205import getStdin from 'get-stdin';206207const content = await getStdin();208```209210### Variable substitution211212```sh213# Bash214echo $LANG215```216217```js218// zx219await $`echo $LANG`;220```221222```js223// Execa224await $`echo ${process.env.LANG}`;225```226227### Environment variables228229```sh230# Bash231EXAMPLE=1 example_command232```233234```js235// zx236$.env.EXAMPLE = '1';237await $`example_command`;238delete $.env.EXAMPLE;239```240241```js242// Execa243await $({env: {EXAMPLE: '1'}})`example_command`;244```245246### Escaping247248```sh249# Bash250echo 'one two'251```252253```js254// zx255await $`echo ${'one two'}`;256```257258```js259// Execa260await $`echo ${'one two'}`;261```262263### Escaping multiple arguments264265```sh266# Bash267echo 'one two' '$'268```269270```js271// zx272await $`echo ${['one two', '$']}`;273```274275```js276// Execa277await $`echo ${['one two', '$']}`;278```279280### Current filename281282```sh283# Bash284echo "$(basename "$0")"285```286287```js288// zx289await $`echo ${__filename}`;290```291292```js293// Execa294import {fileURLToPath} from 'node:url';295import path from 'node:path';296297const __filename = path.basename(fileURLToPath(import.meta.url));298299await $`echo ${__filename}`;300```301302### Verbose mode303304```sh305# Bash306set -v307echo example308```309310```js311// zx >=8312await $`echo example`.verbose();313314// or:315$.verbose = true;316```317318```js319// Execa320const $$ = $({verbose: true});321await $$`echo example`;322```323324Or:325326```327NODE_DEBUG=execa node file.js328```329330### Current directory331332```sh333# Bash334cd project335```336337```js338// zx339cd('project');340341// or:342$.cwd = 'project';343```344345```js346// Execa347const $$ = $({cwd: 'project'});348```349350### Multiple current directories351352```sh353# Bash354pushd project355pwd356popd357pwd358```359360```js361// zx362within(async () => {363 cd('project');364 await $`pwd`;365});366367await $`pwd`;368```369370```js371// Execa372await $({cwd: 'project'})`pwd`;373await $`pwd`;374```375376### Exit codes377378```sh379# Bash380false381echo $?382```383384```js385// zx386const {exitCode} = await $`false`.nothrow();387echo`${exitCode}`;388```389390```js391// Execa392const {exitCode} = await $({reject: false})`false`;393console.log(exitCode);394```395396### Timeouts397398```sh399# Bash400timeout 5 echo example401```402403```js404// zx405await $`echo example`.timeout('5s');406```407408```js409// Execa410await $({timeout: 5000})`echo example`;411```412413### PID414415```sh416# Bash417echo example &418echo $!419```420421```js422// zx does not return `childProcess.pid`423```424425```js426// Execa427const {pid} = $`echo example`;428```429430### Errors431432```sh433# Bash communicates errors only through the exit code and stderr434timeout 1 sleep 2435echo $?436```437438```js439// zx440const {441 stdout,442 stderr,443 exitCode,444 signal,445} = await $`sleep 2`.timeout('1s');446// file:///home/me/Desktop/node_modules/zx/build/core.js:146447// let output = new ProcessOutput(code, signal, stdout, stderr, combined, message);448// ^449// ProcessOutput [Error]:450// at file:///home/me/Desktop/example.js:2:20451// exit code: null452// signal: SIGTERM453// at ChildProcess.<anonymous> (file:///home/me/Desktop/node_modules/zx/build/core.js:146:26)454// at ChildProcess.emit (node:events:512:28)455// at maybeClose (node:internal/child_process:1098:16)456// at Socket.<anonymous> (node:internal/child_process:456:11)457// at Socket.emit (node:events:512:28)458// at Pipe.<anonymous> (node:net:316:12)459// at Pipe.callbackTrampoline (node:internal/async_hooks:130:17) {460// _code: null,461// _signal: 'SIGTERM',462// _stdout: '',463// _stderr: '',464// _combined: ''465// }466```467468```js469// Execa470const {471 stdout,472 stderr,473 exitCode,474 signal,475 signalDescription,476 originalMessage,477 shortMessage,478 command,479 escapedCommand,480 failed,481 timedOut,482 isCanceled,483 killed,484 // and other error-related properties: code, etc.485} = await $({timeout: 1})`sleep 2`;486// file:///home/me/code/execa/lib/kill.js:60487// reject(Object.assign(new Error('Timed out'), {timedOut: true, signal}));488// ^489// Error: Command timed out after 1 milliseconds: sleep 2490// Timed out491// at file:///home/me/Desktop/example.js:2:20492// timedOut: true,493// signal: 'SIGTERM',494// originalMessage: 'Timed out',495// shortMessage: 'Command timed out after 1 milliseconds: sleep 2\nTimed out',496// command: 'sleep 2',497// escapedCommand: 'sleep 2',498// exitCode: undefined,499// signalDescription: 'Termination',500// stdout: '',501// stderr: '',502// failed: true,503// isCanceled: false,504// killed: false505// }506```507508### Shared options509510```sh511# Bash512options="timeout 5"513$options echo one514$options echo two515$options echo three516```517518```js519// zx520const timeout = '5s';521await $`echo one`.timeout(timeout);522await $`echo two`.timeout(timeout);523await $`echo three`.timeout(timeout);524```525526```js527// Execa528const $$ = $({timeout: 5000});529await $$`echo one`;530await $$`echo two`;531await $$`echo three`;532```533534### Background processes535536```sh537# Bash538echo one &539```540541```js542// zx does not allow setting the `detached` option543```544545```js546// Execa547await $({detached: true})`echo one`;548```549550### Printing to stdout551552```sh553# Bash554echo example555```556557```js558// zx559echo`example`;560```561562```js563// Execa564console.log('example');565```566567### Piping stdout to another command568569```sh570# Bash571echo example | cat572```573574```js575// zx576await $`echo example | cat`;577```578579```js580// Execa581await $`echo example`.pipeStdout($`cat`);582```583584### Piping stdout and stderr to another command585586```sh587# Bash588echo example |& cat589```590591```js592// zx593const echo = $`echo example`;594const cat = $`cat`;595echo.pipe(cat)596echo.stderr.pipe(cat.stdin);597await Promise.all([echo, cat]);598```599600```js601// Execa602await $`echo example`.pipeAll($`cat`);603```604605### Piping stdout to a file606607```sh608# Bash609echo example > file.txt610```611612```js613// zx614await $`echo example`.pipe(fs.createWriteStream('file.txt'));615```616617```js618// Execa619await $`echo example`.pipeStdout('file.txt');620```621622### Piping stdin from a file623624```sh625# Bash626echo example < file.txt627```628629```js630// zx631const cat = $`cat`632fs.createReadStream('file.txt').pipe(cat.stdin)633await cat634```635636```js637// Execa

Fix documentation about piping from stdin (#536)ehmickybefore adoption4857cc4

line 638why, one step back
638await $({input: fs.createReadStream('file.txt')})`cat`

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

lines 639–656why, one step back
639```
640641### Silent stderr642643```sh644# Bash645echo example 2> /dev/null646```647648```js649// zx650await $`echo example`.stdio('inherit', 'pipe', 'ignore');651```652653```js654// Execa does not forward stdout/stderr by default655await $`echo example`;656```