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
Provenance
- Commit
aca3db3- Tree
128066c- Author
ehmicky <ehmicky@users.noreply.github.com>- Committer
GitHub <noreply@github.com>- Parent
24e49fe
7 files changed+149 added−138 removed
modified:docs/debugging.md+19 added-11 removed
47 unmodified lines484950515252535455569 unmodified lines6667686970717272737474757677757677787980818283848586877 unmodified lines9596979893991009596979810110210310410510610710810911011111211347 unmodified lines// build.jsawait execa({verbose: 'short'})`npm run build`;```
```sh```$ node build.js[20:36:11.043] [0] $ npm run build[20:36:11.885] [0] ✔ (done in 842ms)```9 unmodified lines
```js// build.jsawait execa({verbose: 'full'})`npm run build`;await execa({verbose: 'full'})`npm run test`;```
```sh```$ node build.js[20:36:11.043] [0] $ npm run buildBuilding application...Done building.[20:36:11.885] [0] ✔ (done in 842ms)[00:57:44.581] [0] $ npm run build[00:57:44.653] [0] Building application...[00:57:44.653] [0] Done building.[00:57:44.658] [0] ✔ (done in 78ms)[00:57:44.658] [1] $ npm run test[00:57:44.740] [1] Running tests...[00:57:44.740] [1] Error: the entrypoint is invalid.[00:57:44.747] [1] ✘ Command failed with exit code 1: npm run test[00:57:44.747] [1] ✘ (done in 89ms)```
### Global mode
7 unmodified lines// This is not loggedawait execa({verbose: 'none'})`npm run test`;```
```sh```$ NODE_DEBUG=execa node build.js[20:36:11.043] [0] $ npm run buildBuilding application...Done building.[20:36:11.885] [0] ✔ (done in 842ms)```
### Colors
When printed to a terminal, the verbose mode uses colors.
<img alt="execa verbose output" src="../media/verbose.png" width="603">
<hr>
[**Next**: 📎 Windows](windows.md)\[**Previous**: 📞 Inter-process communication](ipc.md)\[**Top**: Table of contents](../readme.md#documentation)modified:docs/environment.md+3 added-3 removed
24 unmodified lines252627282929303132332 unmodified lines363738394040414243444546464748495025 unmodified lines24 unmodified lines## Local binaries
Package managers like `npm` install local binaries in `./node_modules/.bin`.
```js```sh$ npm install -D eslint```
```js2 unmodified lines
The [`preferLocal`](api.md#optionspreferlocal) option can be used to execute those local binaries.
```jsawait execa('eslint', {preferLocal: true});await execa({preferLocal: true})`eslint`;```
Those are searched in the current or any parent directory. The [`localDir`](api.md#optionslocaldir) option can select a different directory.
```jsawait execa('eslint', {preferLocal: true, localDir: '/path/to/dir'});await execa({preferLocal: true, localDir: '/path/to/dir'})`eslint`;```
## Current package's binary
25 unmodified linesmodified:docs/escaping.md+2 added
41 unmodified lines42 43 This 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.44 45 ```js46+import {execaCommand} from 'execa';47+48 for await (const commandAndArguments of getReplLine()) {49 await execaCommand(commandAndArguments);50 }51 ```38 unmodified linesmodified:docs/node.md+5 added-5 removed
9 unmodified lines10 11 ```js12 import {execaNode, execa} from 'execa';13 14-await execaNode('file.js');14+await execaNode`file.js argument`;15 // Is the same as:16-await execa('file.js', {node: true});16+await execa({node: true})`file.js argument`;17 // Or:18-await execa('node', ['file.js']);18+await execa`node file.js argument`;19 ```20 21 ## Node.js [CLI flags](https://nodejs.org/api/cli.html#options)22 23 ```js24-await execaNode('file.js', {nodeOptions: ['--no-warnings']});24+await execaNode({nodeOptions: ['--no-warnings']})`file.js argument`;25 ```26 27 ## Node.js version28 3 unmodified lines32 import {execaNode} from 'execa';33 import getNode from 'get-node';34 35 const {path: nodePath} = await getNode('16.2.0');36-await execaNode('file.js', {nodePath});36+await execaNode({nodePath})`file.js argument`;37 ```38 39 <hr>40 3 unmodified linesmodified:docs/scripts.md+1 added-2 removed
15 unmodified lines16 17 ```js18 import {$} from 'execa';19 20-const {stdout: name} = await $`cat package.json`21- .pipe`grep name`;20+const {stdout: name} = await $`cat package.json`.pipe`grep name`;21 console.log(name);22 23 const branch = await $`git branch --show-current`;24 await $`dep deploy --branch=${branch}`;29 unmodified linesadded:media/verbose.pngbinary
A binary file, added.
modified:readme.md+119 added-117 removed
41 unmodified lines42 ---43 44 <br>45 46-## Why46+Execa 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.47 48-This package improves [`child_process`](https://nodejs.org/api/child_process.html) methods with:48+## Features49 50-- [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).65 66 ## Install67 68 ```sh27 unmodified lines96 - 📎 [Windows](docs/windows.md)97 - 🔍 [Difference with Bash and zx](docs/bash.md)98 - 📔 [API reference](docs/api.md)99 100-## Usage100+## Examples101 102-### Promise interface102+### Execution103 104+#### Simple syntax105+106 ```js107 import {execa} from 'execa';108 107-const {stdout} = await execa('echo', ['unicorns']);109+const {stdout} = await execa`npm run build`;110+// Print command's output111 console.log(stdout);109-//=> 'unicorns'112 ```113 112-#### Global/shared options114+#### Script115 116 ```js115-import {execa as execa_} from 'execa';117+import {$} from 'execa';118 117-const execa = execa_({verbose: 'full'});119+const {stdout: name} = await $`cat package.json`.pipe`grep name`;120+console.log(name);121 119-await execa('echo', ['unicorns']);120-//=> 'unicorns'121-```122+const branch = await $`git branch --show-current`;123+await $`dep deploy --branch=${branch}`;124 123-### Template string syntax125+await Promise.all([126+ $`sleep 1`,127+ $`sleep 2`,128+ $`sleep 3`,129+]);130 125-#### Basic131+const directoryName = 'foo bar';132+await $`mkdir /tmp/${directoryName}`;133+```134 127-```js128-import {execa} from 'execa';135+#### Local binaries136 130-const arg = 'unicorns';131-const {stdout} = await execa`echo ${arg} & rainbows!`;132-console.log(stdout);133-//=> 'unicorns & rainbows!'137+```sh138+$ npm install -D eslint139 ```140 136-#### Multiple arguments137-141 ```js139-import {execa} from 'execa';140-141-const args = ['unicorns', '&', 'rainbows!'];142-const {stdout} = await execa`echo ${args}`;143-console.log(stdout);144-//=> 'unicorns & rainbows!'142+await execa({preferLocal: true})`eslint`;143 ```144 147-#### With options145+#### Pipe multiple subprocesses146 147 ```js150-import {execa} from 'execa';148+const {stdout, pipedFrom} = await execa`npm run build`149+ .pipe`sort`150+ .pipe`head -n 2`;151 152-await execa({verbose: 'full'})`echo unicorns`;153-//=> 'unicorns'152+// Output of `npm run build | sort | head -n 2`153+console.log(stdout);154+// Output of `npm run build | sort`155+console.log(pipedFrom[0].stdout);156+// Output of `npm run build`157+console.log(pipedFrom[0].pipedFrom[0].stdout);158 ```159 156-### Scripts160+### Input/output161 158-#### Basic162+#### Interleaved output163 164 ```js161-import {$} from 'execa';162-163-const branch = await $`git branch --show-current`;164-await $`dep deploy --branch=${branch}`;165+const {all} = await execa({all: true})`npm run build`;166+// stdout + stderr, interleaved167+console.log(all);168 ```169 167-#### Verbose mode170+#### Programmatic + terminal output171 169-```sh170-> node file.js171-unicorns172-rainbows173-174-> NODE_DEBUG=execa node file.js175-[19:49:00.360] [0] $ echo unicorns176-unicorns177-[19:49:00.383] [0] √ (done in 23ms)178-[19:49:00.383] [1] $ echo rainbows179-rainbows180-[19:49:00.404] [1] √ (done in 21ms)172+```js173+const {stdout} = await execa({stdout: ['pipe', 'inherit']})`npm run build`;174+// stdout is also printed to the terminal175+console.log(stdout);176 ```177 183-### Input/output178+#### Files179 185-#### Redirect output to a file186-180 ```js188-import {execa} from 'execa';189-190-// Similar to `echo unicorns > stdout.txt` in Bash191-await execa('echo', ['unicorns'], {stdout: {file: 'stdout.txt'}});192-193-// Similar to `echo unicorns 2> stdout.txt` in Bash194-await execa('echo', ['unicorns'], {stderr: {file: 'stderr.txt'}});195-196-// Similar to `echo unicorns &> stdout.txt` in Bash197-await execa('echo', ['unicorns'], {stdout: {file: 'all.txt'}, stderr: {file: 'all.txt'}});181+// Similar to: npm run build > output.txt182+await execa({stdout: {file: './output.txt'}})`npm run build`;183 ```184 200-#### Redirect input from a file185+#### Simple input186 187 ```js203-import {execa} from 'execa';204-205-// Similar to `cat < stdin.txt` in Bash206-const {stdout} = await execa('cat', {inputFile: 'stdin.txt'});188+const {stdout} = await execa({input: getInputString()})`sort`;189 console.log(stdout);208-//=> 'unicorns'190 ```191 211-#### Save and pipe output from a subprocess192+#### Split into text lines193 194 ```js214-import {execa} from 'execa';195+const {stdout} = await execa({lines: true})`npm run build`;196+// Print first 10 lines197+console.log(stdout.slice(0, 10).join('\n'));198+```199 216-const {stdout} = await execa('echo', ['unicorns'], {stdout: ['pipe', 'inherit']});217-// Prints `unicorns`218-console.log(stdout);219-// Also returns 'unicorns'200+### Streaming201+202+#### Iterate over text lines203+204+```js205+for await (const line of execa`npm run build`) {206+ if (line.includes('WARN')) {207+ console.warn(line);208+ }209+}210 ```211 222-#### Pipe multiple subprocesses212+#### Transform/filter output213 214 ```js225-import {execa} from 'execa';215+let count = 0;216 227-// Similar to `npm run build | sort | head -n2` in Bash228-const {stdout, pipedFrom} = await execa('npm', ['run', 'build'])229- .pipe('sort')230- .pipe('head', ['-n2']);231-console.log(stdout); // Result of `head -n2`232-console.log(pipedFrom[0]); // Result of `sort`233-console.log(pipedFrom[0].pipedFrom[0]); // Result of `npm run build`217+// Filter out secret lines, then prepend the line number218+const transform = function * (line) {219+ if (!line.includes('secret')) {220+ yield `[${count++}] ${line}`;221+ }222+};223+224+await execa({stdout: transform})`npm run build`;225 ```226 236-#### Pipe with template strings227+#### Web streams228 229 ```js239-import {execa} from 'execa';240-241-await execa`npm run build`242- .pipe`sort`243- .pipe`head -n2`;230+const response = await fetch('https://example.com');231+await execa({stdin: response.body})`sort`;232 ```233 246-#### Iterate over output lines234+#### Convert to Duplex stream235 236 ```js237 import {execa} from 'execa';238+import {pipeline} from 'node:stream/promises';239+import {createReadStream, createWriteStream} from 'node:fs';240 251-for await (const line of execa`npm run build`)) {252- if (line.includes('ERROR')) {253- console.log(line);254- }255-}241+await pipeline(242+ createReadStream('./input.txt'),243+ execa`node ./transform.js`.duplex(),244+ createWriteStream('./output.txt'),245+);246 ```247 258-### Handling Errors248+### Debugging249 250+#### Detailed error251+252 ```js261-import {execa} from 'execa';253+import {execa, ExecaError} from 'execa';254 263-// Catching an error255 try {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 lines292 */293 }294 ```295 296+#### Verbose mode297+298+```js299+await execa`npm run build`;300+await execa`npm run test`;301+```302+303+<img alt="execa verbose output" src="media/verbose.png" width="603">304+305 ## Related306 307 - [gulp-execa](https://github.com/ehmicky/gulp-execa) - Gulp plugin for Execa308 - [nvexeca](https://github.com/ehmicky/nvexeca) - Run Execa using any Node.js version5 unmodified lines