execution.md
This file
Path
docs/execution.md
137 lines · 4.7 KiB · Markdown
Last changed by
Add `exchangeMessage()` method (#1077)ehmickybefore adoption7a0a1c6
History of this fileTake it
execution.md
▶️ Basic execution
Array syntax
import {execa} from 'execa';
await execa('npm', ['run', 'build']);
Template string syntax
All available methods can use either the array syntax or the template string syntax, which are equivalent.
await execa`npm run build`;
String argument
await execa`npm run ${'task with space'}`;
Number argument
await execa`npm run build --concurrency ${2}`;
Subcommands
const result = await execa`get-concurrency`;
// Uses `result.stdout`
await execa`npm run build --concurrency ${result}`;
Concatenation
const tmpDirectory = '/tmp';
await execa`mkdir ${tmpDirectory}/filename`;
Multiple arguments
const result = await execa`get-concurrency`;
await execa`npm ${['run', 'build', '--concurrency', 2]}`;
Multiple lines
await execa`npm run build
--concurrency 2
--fail-fast`;
Options
Options can be passed to influence the execution's behavior.
Array syntax
await execa('npm', ['run', 'build'], {timeout: 5000});
Template string syntax
await execa({timeout: 5000})`npm run build`;
Global/shared options
const timedExeca = execa({timeout: 5000});
await timedExeca('npm', ['run', 'build']);
await timedExeca`npm run test`;
Return value
Subprocess
The subprocess is returned as soon as it is spawned. It is a child_process instance with additional methods and properties.
const subprocess = execa`npm run build`;
console.log(subprocess.pid);
Result
The subprocess is also a Promise that resolves with the result.
const {stdout} = await execa`npm run build`;
Synchronous execution
Every method can be called synchronously by appending Sync to the method's name. The result is returned without needing to await. The subprocess is not returned: its methods and properties are not available.
import {execaSync} from 'execa';
const {stdout} = execaSync`npm run build`;
Synchronous execution is generally discouraged as it holds the CPU and prevents parallelization. Also, the following features cannot be used:
- Streams:
subprocess.stdin,subprocess.stdout,subprocess.stderr,subprocess.readable(),subprocess.writable(),subprocess.duplex(). - The
stdin,stdout,stderrandstdiooptions cannot be'overlapped', an async iterable, an async transform, aDuplex, nor a web stream. Node.js streams can be passed but only if either they have a file descriptor, or theinputoption is used. - Signal termination:
subprocess.kill(),subprocess.pid,cleanupoption,cancelSignaloption,forceKillAfterDelayoption. - Piping multiple subprocesses:
subprocess.pipe(). subprocess.iterable().- IPC:
sendMessage(),getOneMessage(),exchangeMessage(),getEachMessage(),result.ipcOutput,ipcoption,serializationoption,ipcInputoption. result.allis not interleaved.detachedoption.- The
maxBufferoption is always measured in bytes, not in characters, lines nor objects. Also, it ignores transforms and theencodingoption.