Skip to content
Myr

Improve `readme.md` (#999)

Before adoption: this commit came in with the history the project adopted, so no landing records it.

authored by ehmicky · committed by GitHub · parent 24e49fe · Browse files · 7 files+149 added−138 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

7 files+149 added−138 removed

  • other:+149 added−138 removed

7 files+149 added−138 removed

modified:docs/debugging.md+19 added-11 removed
modified:docs/environment.md+3 added-3 removed
modified:docs/escaping.md+2 added
41 unmodified lines
4243This is only intended for very specific cases, such as a [REPL](https://en.wikipedia.org/wiki/Read%E2%80%93eval%E2%80%93print_loop). This should be avoided otherwise.4445```js46import {execaCommand} from 'execa';4748for await (const commandAndArguments of getReplLine()) {49 await execaCommand(commandAndArguments);50}51```
38 unmodified lines
modified:docs/node.md+5 added-5 removed
9 unmodified lines
1011```js12import {execaNode, execa} from 'execa';1314await execaNode('file.js');14await execaNode`file.js argument`;15// Is the same as:16await execa('file.js', {node: true});16await execa({node: true})`file.js argument`;17// Or:18await execa('node', ['file.js']);18await execa`node file.js argument`;19```2021## Node.js [CLI flags](https://nodejs.org/api/cli.html#options)2223```js24await execaNode('file.js', {nodeOptions: ['--no-warnings']});24await execaNode({nodeOptions: ['--no-warnings']})`file.js argument`;25```2627## Node.js version28
3 unmodified lines
32import {execaNode} from 'execa';33import getNode from 'get-node';3435const {path: nodePath} = await getNode('16.2.0');36await execaNode('file.js', {nodePath});36await execaNode({nodePath})`file.js argument`;37```3839<hr>40
3 unmodified lines
modified:docs/scripts.md+1 added-2 removed
15 unmodified lines
1617```js18import {$} from 'execa';1920const {stdout: name} = await $`cat package.json`21 .pipe`grep name`;20const {stdout: name} = await $`cat package.json`.pipe`grep name`;21console.log(name);2223const branch = await $`git branch --show-current`;24await $`dep deploy --branch=${branch}`;
29 unmodified lines
added:media/verbose.pngbinary

A binary file, added.

modified:readme.md+119 added-117 removed
41 unmodified lines
42---4344<br>4546## Why46Execa runs commands in your script, application or library. Unlike shells, it is [optimized](docs/bash.md) for programmatic usage. Built on top of the [`child_process`](https://nodejs.org/api/child_process.html) core module.4748This package improves [`child_process`](https://nodejs.org/api/child_process.html) methods with:48## Features4950- [Promise interface](docs/execution.md).51- [Script interface](docs/scripts.md) and [template strings](docs/execution.md#template-string-syntax), like `zx`.52- Improved [Windows support](docs/windows.md), including [shebang](docs/windows.md#shebang) binaries.53- Executes [locally installed binaries](docs/environment.md#local-binaries) without `npx`.54- [Cleans up](docs/termination.md#current-process-exit) subprocesses when the current process ends.55- Redirect [`stdin`](docs/input.md)/[`stdout`](docs/output.md)/[`stderr`](docs/output.md) from/to [files](docs/output.md#file-output), [streams](docs/streams.md), [iterables](docs/streams.md#iterables-as-input), [strings](docs/input.md#string-input), [`Uint8Array`](docs/binary.md#binary-input) or [objects](docs/transform.md#object-mode).56- [Transform](docs/transform.md) `stdin`/`stdout`/`stderr` with simple functions.57- Iterate over [each text line](docs/lines.md#progressive-splitting) output by the subprocess.58- [Fail-safe subprocess termination](docs/termination.md#forceful-termination).59- Get [interleaved output](docs/output.md#interleaved-output) from `stdout` and `stderr` similar to what is printed on the terminal.60- [Strips the final newline](docs/lines.md#final-newline) from the output so you don't have to do `stdout.trim()`.61- Convenience methods to [pipe multiple subprocesses](docs/pipe.md).62- [Verbose mode](docs/debugging.md#verbose-mode) for debugging.63- More descriptive [errors](docs/errors.md).64- Higher [max buffer](docs/output.md#big-output): 100 MB instead of 1 MB.50- [Simple syntax](#simple-syntax): promises and [template strings](docs/execution.md#template-string-syntax), like [`zx`](docs/bash.md).51- [Script](#script) interface.52- [No escaping](docs/escaping.md) nor quoting needed. No risk of shell injection.53- Execute [locally installed binaries](#local-binaries) without `npx`.54- Improved [Windows support](docs/windows.md): [shebangs](docs/windows.md#shebang), [`PATHEXT`](https://ss64.com/nt/path.html#pathext), [and more](https://github.com/moxystudio/node-cross-spawn?tab=readme-ov-file#why).55- [Detailed errors](#detailed-error) and [verbose mode](#verbose-mode), for [debugging](docs/debugging.md).56- [Pipe multiple subprocesses](#pipe-multiple-subprocesses) better than in shells: retrieve [intermediate results](docs/pipe.md#result), use multiple [sources](docs/pipe.md#multiple-sources-1-destination)/[destinations](docs/pipe.md#1-source-multiple-destinations), [unpipe](docs/pipe.md#unpipe).57- [Split](#split-into-text-lines) the output into text lines, or [iterate](#iterate-over-text-lines) progressively over them.58- Strip [unnecessary newlines](docs/lines.md#newlines).59- Get [interleaved output](#interleaved-output) from `stdout` and `stderr` similar to what is printed on the terminal.60- Retrieve the output [programmatically and print it](#programmatic--terminal-output) on the console at the same time.61- [Transform or filter](#transformfilter-output) the input and output with [simple functions](docs/transform.md).62- Redirect the [input](docs/input.md) and [output](docs/output.md) from/to [files](#files), [strings](#simple-input), [`Uint8Array`s](docs/binary.md#binary-input), [iterables](docs/streams.md#iterables-as-input) or [objects](docs/transform.md#object-mode).63- Pass [Node.js streams](docs/streams.md#nodejs-streams) or [web streams](#web-streams) to subprocesses, or [convert](#convert-to-duplex-stream) subprocesses to [a stream](docs/streams.md#converting-a-subprocess-to-a-stream).64- Ensure subprocesses exit even when they [intercept termination signals](docs/termination.md#forceful-termination), or when the current process [ends abruptly](docs/termination.md#current-process-exit).6566## Install6768```sh
27 unmodified lines
96- 📎 [Windows](docs/windows.md)97- 🔍 [Difference with Bash and zx](docs/bash.md)98- 📔 [API reference](docs/api.md)99100## Usage100## Examples101102### Promise interface102### Execution103104#### Simple syntax105106```js107import {execa} from 'execa';108107const {stdout} = await execa('echo', ['unicorns']);109const {stdout} = await execa`npm run build`;110// Print command's output111console.log(stdout);109//=> 'unicorns'112```113112#### Global/shared options114#### Script115116```js115import {execa as execa_} from 'execa';117import {$} from 'execa';118117const execa = execa_({verbose: 'full'});119const {stdout: name} = await $`cat package.json`.pipe`grep name`;120console.log(name);121119await execa('echo', ['unicorns']);120//=> 'unicorns'121```122const branch = await $`git branch --show-current`;123await $`dep deploy --branch=${branch}`;124123### Template string syntax125await Promise.all([126 $`sleep 1`,127 $`sleep 2`,128 $`sleep 3`,129]);130125#### Basic131const directoryName = 'foo bar';132await $`mkdir /tmp/${directoryName}`;133```134127```js128import {execa} from 'execa';135#### Local binaries136130const arg = 'unicorns';131const {stdout} = await execa`echo ${arg} & rainbows!`;132console.log(stdout);133//=> 'unicorns & rainbows!'137```sh138$ npm install -D eslint139```140136#### Multiple arguments137141```js139import {execa} from 'execa';140141const args = ['unicorns', '&', 'rainbows!'];142const {stdout} = await execa`echo ${args}`;143console.log(stdout);144//=> 'unicorns & rainbows!'142await execa({preferLocal: true})`eslint`;143```144147#### With options145#### Pipe multiple subprocesses146147```js150import {execa} from 'execa';148const {stdout, pipedFrom} = await execa`npm run build`149 .pipe`sort`150 .pipe`head -n 2`;151152await execa({verbose: 'full'})`echo unicorns`;153//=> 'unicorns'152// Output of `npm run build | sort | head -n 2`153console.log(stdout);154// Output of `npm run build | sort`155console.log(pipedFrom[0].stdout);156// Output of `npm run build`157console.log(pipedFrom[0].pipedFrom[0].stdout);158```159156### Scripts160### Input/output161158#### Basic162#### Interleaved output163164```js161import {$} from 'execa';162163const branch = await $`git branch --show-current`;164await $`dep deploy --branch=${branch}`;165const {all} = await execa({all: true})`npm run build`;166// stdout + stderr, interleaved167console.log(all);168```169167#### Verbose mode170#### Programmatic + terminal output171169```sh170> node file.js171unicorns172rainbows173174> NODE_DEBUG=execa node file.js175[19:49:00.360] [0] $ echo unicorns176unicorns177[19:49:00.383] [0] √ (done in 23ms)178[19:49:00.383] [1] $ echo rainbows179rainbows180[19:49:00.404] [1] √ (done in 21ms)172```js173const {stdout} = await execa({stdout: ['pipe', 'inherit']})`npm run build`;174// stdout is also printed to the terminal175console.log(stdout);176```177183### Input/output178#### Files179185#### Redirect output to a file186180```js188import {execa} from 'execa';189190// Similar to `echo unicorns > stdout.txt` in Bash191await execa('echo', ['unicorns'], {stdout: {file: 'stdout.txt'}});192193// Similar to `echo unicorns 2> stdout.txt` in Bash194await execa('echo', ['unicorns'], {stderr: {file: 'stderr.txt'}});195196// Similar to `echo unicorns &> stdout.txt` in Bash197await execa('echo', ['unicorns'], {stdout: {file: 'all.txt'}, stderr: {file: 'all.txt'}});181// Similar to: npm run build > output.txt182await execa({stdout: {file: './output.txt'}})`npm run build`;183```184200#### Redirect input from a file185#### Simple input186187```js203import {execa} from 'execa';204205// Similar to `cat < stdin.txt` in Bash206const {stdout} = await execa('cat', {inputFile: 'stdin.txt'});188const {stdout} = await execa({input: getInputString()})`sort`;189console.log(stdout);208//=> 'unicorns'190```191211#### Save and pipe output from a subprocess192#### Split into text lines193194```js214import {execa} from 'execa';195const {stdout} = await execa({lines: true})`npm run build`;196// Print first 10 lines197console.log(stdout.slice(0, 10).join('\n'));198```199216const {stdout} = await execa('echo', ['unicorns'], {stdout: ['pipe', 'inherit']});217// Prints `unicorns`218console.log(stdout);219// Also returns 'unicorns'200### Streaming201202#### Iterate over text lines203204```js205for await (const line of execa`npm run build`) {206 if (line.includes('WARN')) {207 console.warn(line);208 }209}210```211222#### Pipe multiple subprocesses212#### Transform/filter output213214```js225import {execa} from 'execa';215let count = 0;216227// Similar to `npm run build | sort | head -n2` in Bash228const {stdout, pipedFrom} = await execa('npm', ['run', 'build'])229 .pipe('sort')230 .pipe('head', ['-n2']);231console.log(stdout); // Result of `head -n2`232console.log(pipedFrom[0]); // Result of `sort`233console.log(pipedFrom[0].pipedFrom[0]); // Result of `npm run build`217// Filter out secret lines, then prepend the line number218const transform = function * (line) {219 if (!line.includes('secret')) {220 yield `[${count++}] ${line}`;221 }222};223224await execa({stdout: transform})`npm run build`;225```226236#### Pipe with template strings227#### Web streams228229```js239import {execa} from 'execa';240241await execa`npm run build`242 .pipe`sort`243 .pipe`head -n2`;230const response = await fetch('https://example.com');231await execa({stdin: response.body})`sort`;232```233246#### Iterate over output lines234#### Convert to Duplex stream235236```js237import {execa} from 'execa';238import {pipeline} from 'node:stream/promises';239import {createReadStream, createWriteStream} from 'node:fs';240251for await (const line of execa`npm run build`)) {252 if (line.includes('ERROR')) {253 console.log(line);254 }255}241await pipeline(242 createReadStream('./input.txt'),243 execa`node ./transform.js`.duplex(),244 createWriteStream('./output.txt'),245);246```247258### Handling Errors248### Debugging249250#### Detailed error251252```js261import {execa} from 'execa';253import {execa, ExecaError} from 'execa';254263// Catching an error255try {265 await execa('unknown', ['command']);256 await execa`unknown command`;257} catch (error) {258 if (error instanceof ExecaError) {267 console.log(error);259 console.log(error);260 }261 /*262 ExecaError: Command failed with ENOENT: unknown command263 spawn unknown ENOENT264 at ...
27 unmodified lines
292 */293}294```295296#### Verbose mode297298```js299await execa`npm run build`;300await execa`npm run test`;301```302303<img alt="execa verbose output" src="media/verbose.png" width="603">304305## Related306307- [gulp-execa](https://github.com/ehmicky/gulp-execa) - Gulp plugin for Execa308- [nvexeca](https://github.com/ehmicky/nvexeca) - Run Execa using any Node.js version
5 unmodified lines