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

Show it rendered

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>67[![Coverage Status](https://codecov.io/gh/sindresorhus/execa/branch/main/graph/badge.svg)](https://app.codecov.io/gh/sindresorhus/execa)89> 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>25		<br>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>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>40		<br>41		<br>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>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`.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).71- [Detailed errors](#detailed-error), [verbose mode](#verbose-mode) and [custom logging](#custom-logging), for [debugging](docs/debugging.md).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).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).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).81- [Exchange messages](#exchange-messages) with the subprocess.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)116- 🐭 [Small packages](docs/small.md)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```197198#### Simple input199200```js201const getInputString = () => { /* ... */ };202const {stdout} = await execa({input: getInputString()})`sort`;203console.log(stdout);204```205206#### File input207208```js209// Similar to: npm run build < input.txt210await execa({stdin: {file: 'input.txt'}})`npm run build`;211```212213#### File output214215```js216// Similar to: npm run build > output.txt217await execa({stdout: {file: 'output.txt'}})`npm run build`;218```219220#### Split into text lines221222```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);274```275276### IPC277278#### Exchange messages279280```js281// parent.js282import {execaNode} from 'execa';283284const subprocess = execaNode`child.js`;285await subprocess.sendMessage('Hello from parent');286const message = await subprocess.getOneMessage();287console.log(message); // 'Hello from child'288```289290```js291// child.js292import {getOneMessage, sendMessage} from 'execa';293294const message = await getOneMessage(); // 'Hello from parent'295const newMessage = message.replace('parent', 'child'); // 'Hello from child'296await sendMessage(newMessage);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';324325const {ipcOutput} = await execaNode`build.js`;326console.log(ipcOutput[0]); // {kind: 'start', timestamp: date}327console.log(ipcOutput[1]); // {kind: 'stop', timestamp: date}328```329330```js331// build.js332import {sendMessage} from 'execa';333334const runBuild = () => { /* ... */ };335336await sendMessage({kind: 'start', timestamp: new Date()});337await runBuild();338await sendMessage({kind: 'stop', timestamp: new Date()});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});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">423424#### 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```451452## Related453454- [nano-spawn](https://github.com/sindresorhus/nano-spawn) - Like Execa but [smaller](docs/small.md)455- [gulp-execa](https://github.com/ehmicky/gulp-execa) - Gulp plugin for Execa456- [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)