Skip to content
Myr

readme.md

This file

Path

readme.md

461 lines · 11.8 KiB · Markdown

Last changed by

Move away from `cross-spawn` (#1251)Sindre Sorhusbefore adoption4cafc3f

History of this file

Take it

The walk stopped after 200 commits: lines older than 9f65b86 point at it.

100% test coverage (#1018)ehmickybefore adoption9f65b86

lines 1–6why, one step back
1<picture>
2 <source media="(prefers-color-scheme: dark)" srcset="media/logo_dark.svg">3 <img alt="execa logo" src="media/logo.svg" width="400">4</picture>5<br>6

Move away from `cross-spawn` (#1251)Sindre Sorhusbefore adoption4cafc3f

line 7why, one step back
7[![Coverage Status](https://codecov.io/gh/sindresorhus/execa/branch/main/graph/badge.svg)](https://app.codecov.io/gh/sindresorhus/execa)

100% test coverage (#1018)ehmickybefore adoption9f65b86

lines 8–24why, one step back
8
9> Process execution for humans1011<br>1213---1415<div align="center">16 <p>17 <p>18 <sup>19 <a href="https://github.com/sponsors/sindresorhus">Sindre's open source work is supported by the community</a>20 </sup>21 </p>22 <sup>Special thanks to:</sup>23 <br>24 <br>

Meta tweaksSindre Sorhusbefore adoption9a2cb79

line 25why, one step back
25 <br>

100% test coverage (#1018)ehmickybefore adoption9f65b86

lines 26–28why, one step back
26 <a href="https://coderabbit.ai?utm_source=sindre&utm_medium=execa">
27 <img width="300" src="https://sindresorhus.com/assets/thanks/coderabbit-logo.png" alt="CodeRabbit logo">28 </a>

Meta tweaksSindre Sorhusbefore adoption9a2cb79

lines 29–39why, one step back
29 <br>
30 <br>31 <br>32 <a href="https://kruu.com">33 <picture>34 <source srcset="https://sindresorhus.com/assets/thanks/kruu-logo-dark.svg?y" media="(prefers-color-scheme: dark)" width="260">35 <source srcset="https://sindresorhus.com/assets/thanks/kruu-logo-light.svg?y" media="(prefers-color-scheme: light)" width="260">36 <img src="https://sindresorhus.com/assets/thanks/kruu-logo-light.svg?y" width="260"alt="KRUU logo">37 </picture>38 </a>39 <br>

100% test coverage (#1018)ehmickybefore adoption9f65b86

lines 40–41why, one step back
40 <br>
41 <br>

Meta tweaksSindre Sorhusbefore adoption103095f

lines 42–54why, one step back
42 <a href="https://depot.dev?utm_source=github&utm_medium=sindresorhus">
43 <div>44 <picture>45 <source width="180" media="(prefers-color-scheme: dark)" srcset="https://sindresorhus.com/assets/thanks/depot-logo-dark.svg">46 <source width="180" media="(prefers-color-scheme: light)" srcset="https://sindresorhus.com/assets/thanks/depot-logo-light.svg">47 <img width="180" src="https://sindresorhus.com/assets/thanks/depot-logo-light.svg" alt="Depot logo">48 </picture>49 </div>50 <b>Fast remote container builds and GitHub Actions runners.</b>51 </a>52 <br>53 <br>54 <br>

100% test coverage (#1018)ehmickybefore adoption9f65b86

lines 55–69why, one step back
55 </p>
56</div>5758---5960<br>6162Execa 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.6364## Features6566- [Simple syntax](#simple-syntax): promises and [template strings](docs/execution.md#template-string-syntax), like [`zx`](docs/bash.md).67- [Script](#script) interface.68- [No escaping](docs/escaping.md) nor quoting needed. No risk of shell injection.69- Execute [locally installed binaries](#local-binaries) without `npx`.

Move away from `cross-spawn` (#1251)Sindre Sorhusbefore adoption4cafc3f

line 70why, one step back
70- Improved [Windows support](docs/windows.md): [shebangs](docs/windows.md#shebang), [`PATHEXT`](https://ss64.com/nt/path.html#pathext), [graceful termination](#graceful-termination), [and more](docs/windows.md).

Add custom logging section to `readme.md` (#1131)ehmickybefore adoption6c6e861

line 71why, one step back
71- [Detailed errors](#detailed-error), [verbose mode](#verbose-mode) and [custom logging](#custom-logging), for [debugging](docs/debugging.md).

100% test coverage (#1018)ehmickybefore adoption9f65b86

lines 72–74why, one step back
72- [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).
73- [Split](#split-into-text-lines) the output into text lines, or [iterate](#iterate-over-text-lines) progressively over them.74- Strip [unnecessary newlines](docs/lines.md#newlines).

Add `ipcInput` option (#1068)ehmickybefore adoption46cae30

lines 75–76why, one step back
75- Pass any [input](docs/input.md) to the subprocess: [files](#file-input), [strings](#simple-input), [`Uint8Array`s](docs/binary.md#binary-input), [iterables](docs/streams.md#iterables-as-input), [objects](docs/transform.md#object-mode) and almost any [other type](#any-input-type).
76- Return [almost any type](#any-output-type) from the subprocess, or redirect it to [files](#file-output).

100% test coverage (#1018)ehmickybefore adoption9f65b86

lines 77–80why, one step back
77- Get [interleaved output](#interleaved-output) from `stdout` and `stderr` similar to what is printed on the terminal.
78- Retrieve the output [programmatically and print it](#programmatic--terminal-output) on the console at the same time.79- [Transform or filter](#transformfilter-output) the input and output with [simple functions](docs/transform.md).80- 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).

Add promise-based IPC (#1059)ehmickybefore adoptionacc2b68

line 81why, one step back
81- [Exchange messages](#exchange-messages) with the subprocess.

100% test coverage (#1018)ehmickybefore adoption9f65b86

lines 82–115why, one step back
82- 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).
8384## Install8586```sh87npm install execa88```8990## Documentation9192Execution:93- ▶️ [Basic execution](docs/execution.md)94- 💬 [Escaping/quoting](docs/escaping.md)95- 💻 [Shell](docs/shell.md)96- 📜 [Scripts](docs/scripts.md)97- 🐢 [Node.js files](docs/node.md)98- 🌐 [Environment](docs/environment.md)99- ❌ [Errors](docs/errors.md)100- 🏁 [Termination](docs/termination.md)101102Input/output:103- 🎹 [Input](docs/input.md)104- 📢 [Output](docs/output.md)105- 📃 [Text lines](docs/lines.md)106- 🤖 [Binary data](docs/binary.md)107- 🧙 [Transforms](docs/transform.md)108109Advanced usage:110- 🔀 [Piping multiple subprocesses](docs/pipe.md)111- ⏳️ [Streams](docs/streams.md)112- 📞 [Inter-process communication](docs/ipc.md)113- 🐛 [Debugging](docs/debugging.md)114- 📎 [Windows](docs/windows.md)115- 🔍 [Difference with Bash and zx](docs/bash.md)

Add documentation about nano-spawn (#1157)ehmickybefore adoptioneb3cfba

line 116why, one step back
116- 🐭 [Small packages](docs/small.md)

100% test coverage (#1018)ehmickybefore adoption9f65b86

lines 117–197why, one step back
117- 🤓 [TypeScript](docs/typescript.md)
118- 📔 [API reference](docs/api.md)119120## Examples121122### Execution123124#### Simple syntax125126```js127import {execa} from 'execa';128129const {stdout} = await execa`npm run build`;130// Print command's output131console.log(stdout);132```133134#### Script135136```js137import {$} from 'execa';138139const {stdout: name} = await $`cat package.json`.pipe`grep name`;140console.log(name);141142const branch = await $`git branch --show-current`;143await $`dep deploy --branch=${branch}`;144145await Promise.all([146 $`sleep 1`,147 $`sleep 2`,148 $`sleep 3`,149]);150151const directoryName = 'foo bar';152await $`mkdir /tmp/${directoryName}`;153```154155#### Local binaries156157```sh158$ npm install -D eslint159```160161```js162await execa({preferLocal: true})`eslint`;163```164165#### Pipe multiple subprocesses166167```js168const {stdout, pipedFrom} = await execa`npm run build`169 .pipe`sort`170 .pipe`head -n 2`;171172// Output of `npm run build | sort | head -n 2`173console.log(stdout);174// Output of `npm run build | sort`175console.log(pipedFrom[0].stdout);176// Output of `npm run build`177console.log(pipedFrom[0].pipedFrom[0].stdout);178```179180### Input/output181182#### Interleaved output183184```js185const {all} = await execa({all: true})`npm run build`;186// stdout + stderr, interleaved187console.log(all);188```189190#### Programmatic + terminal output191192```js193const {stdout} = await execa({stdout: ['pipe', 'inherit']})`npm run build`;194// stdout is also printed to the terminal195console.log(stdout);196```197

Add `ipcInput` option (#1068)ehmickybefore adoption46cae30

line 198why, one step back
198#### Simple input

100% test coverage (#1018)ehmickybefore adoption9f65b86

lines 199–200why, one step back
199
200```js

Add `gracefulCancel` option (#1109)ehmickybefore adoptiond8190e5

line 201why, one step back
201const getInputString = () => { /* ... */ };

Add `ipcInput` option (#1068)ehmickybefore adoption46cae30

lines 202–203why, one step back
202const {stdout} = await execa({input: getInputString()})`sort`;
203console.log(stdout);

100% test coverage (#1018)ehmickybefore adoption9f65b86

lines 204–205why, one step back
204```
205

Add `ipcInput` option (#1068)ehmickybefore adoption46cae30

line 206why, one step back
206#### File input

100% test coverage (#1018)ehmickybefore adoption9f65b86

lines 207–208why, one step back
207
208```js

Add `ipcInput` option (#1068)ehmickybefore adoption46cae30

lines 209–210why, one step back
209// Similar to: npm run build < input.txt
210await execa({stdin: {file: 'input.txt'}})`npm run build`;

100% test coverage (#1018)ehmickybefore adoption9f65b86

lines 211–212why, one step back
211```
212

Add `ipcInput` option (#1068)ehmickybefore adoption46cae30

lines 213–219why, one step back
213#### File output
214215```js216// Similar to: npm run build > output.txt217await execa({stdout: {file: 'output.txt'}})`npm run build`;218```219

100% test coverage (#1018)ehmickybefore adoption9f65b86

lines 220–273why, one step back
220#### Split into text lines
221222```js223const {stdout} = await execa({lines: true})`npm run build`;224// Print first 10 lines225console.log(stdout.slice(0, 10).join('\n'));226```227228### Streaming229230#### Iterate over text lines231232```js233for await (const line of execa`npm run build`) {234 if (line.includes('WARN')) {235 console.warn(line);236 }237}238```239240#### Transform/filter output241242```js243let count = 0;244245// Filter out secret lines, then prepend the line number246const transform = function * (line) {247 if (!line.includes('secret')) {248 yield `[${count++}] ${line}`;249 }250};251252await execa({stdout: transform})`npm run build`;253```254255#### Web streams256257```js258const response = await fetch('https://example.com');259await execa({stdin: response.body})`sort`;260```261262#### Convert to Duplex stream263264```js265import {execa} from 'execa';266import {pipeline} from 'node:stream/promises';267import {createReadStream, createWriteStream} from 'node:fs';268269await pipeline(270 createReadStream('./input.txt'),271 execa`node ./transform.js`.duplex(),272 createWriteStream('./output.txt'),273);

Add promise-based IPC (#1059)ehmickybefore adoptionacc2b68

lines 274–275why, one step back
274```
275

Add `ipcInput` option (#1068)ehmickybefore adoption46cae30

lines 276–277why, one step back
276### IPC
277

Add promise-based IPC (#1059)ehmickybefore adoptionacc2b68

lines 278–284why, one step back
278#### Exchange messages
279280```js281// parent.js282import {execaNode} from 'execa';283284const subprocess = execaNode`child.js`;

Debounce `message` events (#1087)ehmickybefore adoptione8bab97

lines 285–286why, one step back
285await subprocess.sendMessage('Hello from parent');
286const message = await subprocess.getOneMessage();

Add `exchangeMessage()` method (#1077)ehmickybefore adoption7a0a1c6

line 287why, one step back
287console.log(message); // 'Hello from child'

Add promise-based IPC (#1059)ehmickybefore adoptionacc2b68

lines 288–291why, one step back
288```
289290```js291// child.js

Add `exchangeMessage()` method (#1077)ehmickybefore adoption7a0a1c6

line 292why, one step back
292import {getOneMessage, sendMessage} from 'execa';

Add promise-based IPC (#1059)ehmickybefore adoptionacc2b68

line 293why, one step back
293

Add `exchangeMessage()` method (#1077)ehmickybefore adoption7a0a1c6

lines 294–296why, one step back
294const message = await getOneMessage(); // 'Hello from parent'
295const newMessage = message.replace('parent', 'child'); // 'Hello from child'296await sendMessage(newMessage);

Add `ipcInput` option (#1068)ehmickybefore adoption46cae30

lines 297–324why, one step back
297```
298299#### Any input type300301```js302// main.js303import {execaNode} from 'execa';304305const ipcInput = [306 {task: 'lint', ignore: /test\.js/},307 {task: 'copy', files: new Set(['main.js', 'index.js']),308}];309await execaNode({ipcInput})`build.js`;310```311312```js313// build.js314import {getOneMessage} from 'execa';315316const ipcInput = await getOneMessage();317```318319#### Any output type320321```js322// main.js323import {execaNode} from 'execa';324

Rename `result.ipc` to `result.ipcOutput` (#1075)ehmickybefore adoptionae9b360

lines 325–327why, one step back
325const {ipcOutput} = await execaNode`build.js`;
326console.log(ipcOutput[0]); // {kind: 'start', timestamp: date}327console.log(ipcOutput[1]); // {kind: 'stop', timestamp: date}

Add `ipcInput` option (#1068)ehmickybefore adoption46cae30

lines 328–333why, one step back
328```
329330```js331// build.js332import {sendMessage} from 'execa';333

Add `gracefulCancel` option (#1109)ehmickybefore adoptiond8190e5

lines 334–335why, one step back
334const runBuild = () => { /* ... */ };
335

Add `ipcInput` option (#1068)ehmickybefore adoption46cae30

lines 336–338why, one step back
336await sendMessage({kind: 'start', timestamp: new Date()});
337await runBuild();338await sendMessage({kind: 'stop', timestamp: new Date()});

Add `gracefulCancel` option (#1109)ehmickybefore adoptiond8190e5

lines 339–364why, one step back
339```
340341#### Graceful termination342343```js344// main.js345import {execaNode} from 'execa';346347const controller = new AbortController();348setTimeout(() => {349 controller.abort();350}, 5000);351352await execaNode({353 cancelSignal: controller.signal,354 gracefulCancel: true,355})`build.js`;356```357358```js359// build.js360import {getCancelSignal} from 'execa';361362const cancelSignal = await getCancelSignal();363const url = 'https://example.com/build/info';364const response = await fetch(url, {signal: cancelSignal});

100% test coverage (#1018)ehmickybefore adoption9f65b86

lines 365–422why, one step back
365```
366367### Debugging368369#### Detailed error370371```js372import {execa, ExecaError} from 'execa';373374try {375 await execa`unknown command`;376} catch (error) {377 if (error instanceof ExecaError) {378 console.log(error);379 }380 /*381 ExecaError: Command failed with ENOENT: unknown command382 spawn unknown ENOENT383 at ...384 at ... {385 shortMessage: 'Command failed with ENOENT: unknown command\nspawn unknown ENOENT',386 originalMessage: 'spawn unknown ENOENT',387 command: 'unknown command',388 escapedCommand: 'unknown command',389 cwd: '/path/to/cwd',390 durationMs: 28.217566,391 failed: true,392 timedOut: false,393 isCanceled: false,394 isTerminated: false,395 isMaxBuffer: false,396 code: 'ENOENT',397 stdout: '',398 stderr: '',399 stdio: [undefined, '', ''],400 pipedFrom: []401 [cause]: Error: spawn unknown ENOENT402 at ...403 at ... {404 errno: -2,405 code: 'ENOENT',406 syscall: 'spawn unknown',407 path: 'unknown',408 spawnargs: [ 'command' ]409 }410 }411 */412}413```414415#### Verbose mode416417```js418await execa`npm run build`;419await execa`npm run test`;420```421422<img alt="execa verbose output" src="media/verbose.png" width="603">

Add custom logging section to `readme.md` (#1131)ehmickybefore adoption6c6e861

lines 423–450why, one step back
423
424#### Custom logging425426```js427import {execa as execa_} from 'execa';428import {createLogger, transports} from 'winston';429430// Log to a file using Winston431const transport = new transports.File({filename: 'logs.txt'});432const logger = createLogger({transports: [transport]});433const LOG_LEVELS = {434 command: 'info',435 output: 'verbose',436 ipc: 'verbose',437 error: 'error',438 duration: 'info',439};440441const execa = execa_({442 verbose(verboseLine, {message, ...verboseObject}) {443 const level = LOG_LEVELS[verboseObject.type];444 logger[level](message, verboseObject);445 },446});447448await execa`npm run build`;449await execa`npm run test`;450```

100% test coverage (#1018)ehmickybefore adoption9f65b86

lines 451–453why, one step back
451
452## Related453

Add documentation about nano-spawn (#1157)ehmickybefore adoptioneb3cfba

line 454why, one step back
454- [nano-spawn](https://github.com/sindresorhus/nano-spawn) - Like Execa but [smaller](docs/small.md)

100% test coverage (#1018)ehmickybefore adoption9f65b86

lines 455–461why, one step back
455- [gulp-execa](https://github.com/ehmicky/gulp-execa) - Gulp plugin for Execa
456- [nvexeca](https://github.com/ehmicky/nvexeca) - Run Execa using any Node.js version457458## Maintainers459460- [Sindre Sorhus](https://github.com/sindresorhus)461- [@ehmicky](https://github.com/ehmicky)