Process execution for humans
This package improves child_process
methods with:
- Promise interface.
- Scripts interface, like
zx
. - Improved Windows support, including shebang binaries.
- Executes locally installed binaries without
npx
. - Cleans up child processes when the parent process ends.
- Redirect
stdin
/stdout
/stderr
from/to files, streams, iterables, strings,Uint8Array
or objects. - Transform
stdin
/stdout
/stderr
with simple functions. - Iterate over each text line output by the process.
- Fail-safe process termination.
- Get interleaved output from
stdout
andstderr
similar to what is printed on the terminal. - Strips the final newline from the output so you don't have to do
stdout.trim()
. - Convenience methods to pipe processes' input and output.
- Can specify file and arguments as a single string without a shell.
- Verbose mode for debugging.
- More descriptive errors.
- Higher max buffer: 100 MB instead of 1 MB.
npm install execa
import {execa} from 'execa';
const {stdout} = await execa('echo', ['unicorns']);
console.log(stdout);
//=> 'unicorns'
For more information about Execa scripts, please see this page.
import {$} from 'execa';
const branch = await $`git branch --show-current`;
await $`dep deploy --branch=${branch}`;
import {$} from 'execa';
const args = ['unicorns', '&', 'rainbows!'];
const {stdout} = await $`echo ${args}`;
console.log(stdout);
//=> 'unicorns & rainbows!'
import {$} from 'execa';
await $({stdio: 'inherit'})`echo unicorns`;
//=> 'unicorns'
import {$} from 'execa';
const $$ = $({stdio: 'inherit'});
await $$`echo unicorns`;
//=> 'unicorns'
await $$`echo rainbows`;
//=> 'rainbows'
> node file.js
unicorns
rainbows
> NODE_DEBUG=execa node file.js
[16:50:03.305] echo unicorns
unicorns
[16:50:03.308] echo rainbows
rainbows
import {execa} from 'execa';
// Similar to `echo unicorns > stdout.txt` in Bash
await execa('echo', ['unicorns'], {stdout: {file: 'stdout.txt'}});
// Similar to `echo unicorns 2> stdout.txt` in Bash
await execa('echo', ['unicorns'], {stderr: {file: 'stderr.txt'}});
// Similar to `echo unicorns &> stdout.txt` in Bash
await execa('echo', ['unicorns'], {stdout: {file: 'all.txt'}, stderr: {file: 'all.txt'}});
import {execa} from 'execa';
// Similar to `cat < stdin.txt` in Bash
const {stdout} = await execa('cat', {inputFile: 'stdin.txt'});
console.log(stdout);
//=> 'unicorns'
import {execa} from 'execa';
const {stdout} = await execa('echo', ['unicorns'], {stdout: ['pipe', 'inherit']});
// Prints `unicorns`
console.log(stdout);
// Also returns 'unicorns'
import {execa} from 'execa';
// Similar to `npm run build | sort | head -n2` in Bash
const {stdout, pipedFrom} = await execa('npm', ['run', 'build'])
.pipe(execa('sort'))
.pipe(execa('head', ['-n2']));
console.log(stdout); // Result of `head -n2`
console.log(pipedFrom[0]); // Result of `sort`
console.log(pipedFrom[0].pipedFrom[0]); // Result of `npm run build`
import {execa} from 'execa';
// Catching an error
try {
await execa('unknown', ['command']);
} catch (error) {
console.log(error);
/*
{
message: 'Command failed with ENOENT: unknown command spawn unknown ENOENT',
errno: -2,
code: 'ENOENT',
syscall: 'spawn unknown',
path: 'unknown',
spawnargs: ['command'],
originalMessage: 'spawn unknown ENOENT',
shortMessage: 'Command failed with ENOENT: unknown command spawn unknown ENOENT',
command: 'unknown command',
escapedCommand: 'unknown command',
stdout: '',
stderr: '',
failed: true,
timedOut: false,
isCanceled: false,
isTerminated: false
}
*/
}
Executes a command using file ...arguments
. file
is a string or a file URL. arguments
are an array of strings. Returns a childProcess
.
Arguments are automatically escaped. They can contain any character, including spaces.
This is the preferred method when executing single commands.
Executes a command. The command
string includes both the file
and its arguments
. Returns a childProcess
.
Arguments are automatically escaped. They can contain any character, but spaces must use ${}
like $`echo ${'has space'}`
.
This is the preferred method when executing multiple commands in a script file.
The command
string can inject any ${value}
with the following types: string, number, childProcess
or an array of those types. For example: $`echo one ${'two'} ${3} ${['four', 'five']}`
. For ${childProcess}
, the process's stdout
is used.
For more information, please see this section and this page.
Returns a new instance of $
but with different default options
. Consecutive calls are merged to previous ones.
This can be used to either:
- Set options for a specific command:
$(options)`command`
- Share options for multiple commands:
const $$ = $(options); $$`command`; $$`otherCommand`;
Executes a command. The command
string includes both the file
and its arguments
. Returns a childProcess
.
Arguments are automatically escaped. They can contain any character, but spaces must be escaped with a backslash like execaCommand('echo has\\ space')
.
This is the preferred method when executing a user-supplied command
string, such as in a REPL.
Same as execa()
but using the node
option.
Executes a Node.js file using node scriptPath ...arguments
.
Same as execa()
but synchronous.
Cannot use the following options: all
, cleanup
, buffer
, detached
, ipc
, serialization
, signal
and lines
. Also, the stdin
, stdout
, stderr
, stdio
and input
options cannot be an array, an iterable or a web stream. Node.js streams must have a file descriptor unless the input
option is used.
Returns or throws a childProcessResult
. The childProcess
is not returned: its methods and properties are not available. This includes .kill()
, .pid
, .pipe()
and the .stdin
/.stdout
/.stderr
streams.
Same as $`command` but synchronous.
Cannot use the following options: all
, cleanup
, buffer
, detached
, ipc
, serialization
, signal
and lines
. Also, the stdin
, stdout
, stderr
, stdio
and input
options cannot be an array, an iterable or a web stream. Node.js streams must have a file descriptor unless the input
option is used.
Returns or throws a childProcessResult
. The childProcess
is not returned: its methods and properties are not available. This includes .kill()
, .pid
, .pipe()
and the .stdin
/.stdout
/.stderr
streams.
Same as execaCommand()
but synchronous.
Cannot use the following options: all
, cleanup
, buffer
, detached
, ipc
, serialization
, signal
and lines
. Also, the stdin
, stdout
, stderr
, stdio
and input
options cannot be an array, an iterable or a web stream. Node.js streams must have a file descriptor unless the input
option is used.
Returns or throws a childProcessResult
. The childProcess
is not returned: its methods and properties are not available. This includes .kill()
, .pid
, .pipe()
and the .stdin
/.stdout
/.stderr
streams.
For all the methods above, no shell interpreter (Bash, cmd.exe, etc.) is used unless the shell
option is set. This means shell-specific characters and expressions ($variable
, &&
, ||
, ;
, |
, etc.) have no special meaning and do not need to be escaped.
The return value of all asynchronous methods is both:
- a
Promise
resolving or rejecting with achildProcessResult
. - a
child_process
instance with the following additional methods and properties.
Type: ReadableStream | undefined
Stream combining/interleaving stdout
and stderr
.
This is undefined
if either:
- the
all
option isfalse
(the default value) - both
stdout
andstderr
options are set to'inherit'
,'ignore'
,Stream
orinteger
secondChildProcess
: execa()
return value
pipeOptions
: PipeOptions
Returns: Promise<ChildProcessResult>
Pipe the child process' stdout
to a second Execa child process' stdin
. This resolves with that second process' result. If either process is rejected, this is rejected with that process' error instead.
This can be called multiple times to chain a series of processes.
Multiple child processes can be piped to the same process. Conversely, the same child process can be piped to multiple other processes.
Type: object
Type: "stdout" | "stderr" | "all" | number
Default: "stdout"
Which stream to pipe. A file descriptor number can also be passed.
"all"
pipes both stdout
and stderr
. This requires the all
option to be true
.
Type: AbortSignal
Unpipe the child process when the signal aborts.
The .pipe()
method will be rejected with a cancellation error.
signal
: string | number
error
: Error
Returns: boolean
Sends a signal to the child process. The default signal is the killSignal
option. killSignal
defaults to SIGTERM
, which terminates the child process.
This returns false
when the signal could not be sent, for example when the child process has already exited.
When an error is passed as argument, its message and stack trace are kept in the child process' error. The child process is then terminated with the default signal. This does not emit the error
event.
Type: object
Result of a child process execution. On success this is a plain object. On failure this is also an Error
instance.
The child process fails when:
- its exit code is not
0
- it was terminated with a signal
- timing out
- being canceled
- there's not enough memory or there are already too many child processes
Type: string
The file and arguments that were run, for logging purposes.
This is not escaped and should not be executed directly as a process, including using execa()
or execaCommand()
.
Type: string
Same as command
but escaped.
This is meant to be copied and pasted into a shell, for debugging purposes.
Since the escaping is fairly basic, this should not be executed directly as a process, including using execa()
or execaCommand()
.
Type: string
The current directory in which the command was run.
Type: string | Uint8Array | string[] | Uint8Array[] | unknown[] | undefined
The output of the process on stdout
.
This is undefined
if the stdout
option is set to only 'inherit'
, 'ignore'
, Stream
or integer
. This is an array if the lines
option is true
, or if the stdout
option is a transform in object mode.
Type: string | Uint8Array | string[] | Uint8Array[] | unknown[] | undefined
The output of the process on stderr
.
This is undefined
if the stderr
option is set to only 'inherit'
, 'ignore'
, Stream
or integer
. This is an array if the lines
option is true
, or if the stderr
option is a transform in object mode.
Type: string | Uint8Array | string[] | Uint8Array[] | unknown[] | undefined
The output of the process with stdout
and stderr
interleaved.
This is undefined
if either:
- the
all
option isfalse
(the default value) - both
stdout
andstderr
options are set to only'inherit'
,'ignore'
,Stream
orinteger
This is an array if the lines
option is true
, or if either the stdout
or stderr
option is a transform in object mode.
Type: Array<string | Uint8Array | string[] | Uint8Array[] | unknown[] | undefined>
The output of the process on stdin
, stdout
, stderr
and other file descriptors.
Items are undefined
when their corresponding stdio
option is set to 'inherit'
, 'ignore'
, Stream
or integer
. Items are arrays when their corresponding stdio
option is a transform in object mode.
Type: string
Error message when the child process failed to run. In addition to the underlying error message, it also contains some information related to why the child process errored.
The child process stderr
, stdout
and other file descriptors' output are appended to the end, separated with newlines and not interleaved.
Type: string
This is the same as the message
property except it does not include the child process stdout
/stderr
/stdio
.
Type: string | undefined
Original error message. This is the same as the message
property excluding the child process stdout
/stderr
/stdio
and some additional information added by Execa.
This is undefined
unless the child process exited due to an error
event or a timeout.
Type: boolean
Whether the process failed to run.
Type: boolean
Whether the process timed out.
Type: boolean
Whether the process was canceled using the signal
option.
Type: boolean
Whether the process was terminated by a signal (like SIGTERM
) sent by either:
- The current process.
- Another process. This case is not supported on Windows.
Type: number | undefined
The numeric exit code of the process that was run.
This is undefined
when the process could not be spawned or was terminated by a signal.
Type: string | undefined
The name of the signal (like SIGTERM
) that terminated the process, sent by either:
- The current process.
- Another process. This case is not supported on Windows.
If a signal terminated the process, this property is defined and included in the error message. Otherwise it is undefined
.
Type: string | undefined
A human-friendly description of the signal that was used to terminate the process. For example, Floating point arithmetic error
.
If a signal terminated the process, this property is defined and included in the error message. Otherwise it is undefined
. It is also undefined
when the signal is very uncommon which should seldomly happen.
Type: ChildProcessResult[]
Results of the other processes that were piped into this child process. This is useful to inspect a series of child processes piped with each other.
This array is initially empty and is populated each time the .pipe()
method resolves.
Type: object
This lists all Execa options, including some options which are the same as for child_process#spawn()
/child_process#exec()
.
Type: boolean
Default: true
Setting this to false
resolves the promise with the error instead of rejecting it.
Type: boolean | string | URL
Default: false
If true
, runs file
inside of a shell. Uses /bin/sh
on UNIX and cmd.exe
on Windows. A different shell can be specified as a string. The shell should understand the -c
switch on UNIX or /d /s /c
on Windows.
We recommend against using this option since it is:
- not cross-platform, encouraging shell-specific syntax.
- slower, because of the additional shell interpretation.
- unsafe, potentially allowing command injection.
Type: string | URL
Default: process.cwd()
Current working directory of the child process.
This is also used to resolve the nodePath
option when it is a relative path.
Type: object
Default: process.env
Environment key-value pairs.
Unless the extendEnv
option is false
, the child process also uses the current process' environment variables (process.env
).
Type: boolean
Default: true
If true
, the child process uses both the env
option and the current process' environment variables (process.env
).
If false
, only the env
option is used, not process.env
.
Type: boolean
Default: true
with $
, false
otherwise
Prefer locally installed binaries when looking for a binary to execute.
If you $ npm install foo
, you can then execa('foo')
.
Type: string | URL
Default: process.cwd()
Preferred path to find locally installed binaries in (use with preferLocal
).
Type: boolean
Default: true
with execaNode()
, false
otherwise
If true
, runs with Node.js. The first argument must be a Node.js file.
Type: string[]
Default: process.execArgv
(current Node.js CLI options)
List of CLI options passed to the Node.js executable.
Requires the node
option to be true
.
Type: string | URL
Default: process.execPath
(current Node.js executable)
Path to the Node.js executable.
When the node
option is true
, this is used to to create the child process. When the preferLocal
option is true
, this is used in the child process itself.
For example, this can be used together with get-node
to run a specific Node.js version.
Type: boolean
Default: false
Print each command on stderr
before executing it.
This can also be enabled by setting the NODE_DEBUG=execa
environment variable in the current process.
Type: boolean
Default: true
Whether to return the child process' output using the result.stdout
, result.stderr
, result.all
and result.stdio
properties.
On failure, the error.stdout
, error.stderr
, error.all
and error.stdio
properties are used instead.
When buffer
is false
, the output can still be read using the childProcess.stdout
, childProcess.stderr
, childProcess.stdio
and childProcess.all
streams. If the output is read, this should be done right away to avoid missing any data.
Type: string | Uint8Array | stream.Readable
Write some input to the child process' stdin
.
See also the inputFile
and stdin
options.
Type: string | URL
Use a file as input to the child process' stdin
.
See also the input
and stdin
options.
Type: string | number | stream.Readable | ReadableStream | URL | Uint8Array | Iterable<string> | Iterable<Uint8Array> | Iterable<unknown> | AsyncIterable<string> | AsyncIterable<Uint8Array> | AsyncIterable<unknown> | GeneratorFunction<string> | GeneratorFunction<Uint8Array> | GeneratorFunction<unknown>| AsyncGeneratorFunction<string> | AsyncGeneratorFunction<Uint8Array> | AsyncGeneratorFunction<unknown>
(or a tuple of those types)
Default: inherit
with $
, pipe
otherwise
How to setup the child process' standard input. This can be:
'pipe'
: SetschildProcess.stdin
stream.'overlapped'
: Like'pipe'
but asynchronous on Windows.'ignore'
: Do not usestdin
.'inherit'
: Re-use the current process'stdin
.- an integer: Re-use a specific file descriptor from the current process.
- a Node.js
Readable
stream. { file: 'path' }
object.- a file URL.
- a web
ReadableStream
. - an
Iterable
or anAsyncIterable
- an
Uint8Array
.
This can be an array of values such as ['inherit', 'pipe']
or [filePath, 'pipe']
.
This can also be a generator function to transform the input. Learn more.
Type: string | number | stream.Writable | WritableStream | URL | GeneratorFunction<string> | GeneratorFunction<Uint8Array> | GeneratorFunction<unknown>| AsyncGeneratorFunction<string> | AsyncGeneratorFunction<Uint8Array> | AsyncGeneratorFunction<unknown>
(or a tuple of those types)
Default: pipe
How to setup the child process' standard output. This can be:
'pipe'
: SetschildProcessResult.stdout
(as a string orUint8Array
) andchildProcess.stdout
(as a stream).'overlapped'
: Like'pipe'
but asynchronous on Windows.'ignore'
: Do not usestdout
.'inherit'
: Re-use the current process'stdout
.- an integer: Re-use a specific file descriptor from the current process.
- a Node.js
Writable
stream. { file: 'path' }
object.- a file URL.
- a web
WritableStream
.
This can be an array of values such as ['inherit', 'pipe']
or [filePath, 'pipe']
.
This can also be a generator function to transform the output. Learn more.
Type: string | number | stream.Writable | WritableStream | URL | GeneratorFunction<string> | GeneratorFunction<Uint8Array> | GeneratorFunction<unknown>| AsyncGeneratorFunction<string> | AsyncGeneratorFunction<Uint8Array> | AsyncGeneratorFunction<unknown>
(or a tuple of those types)
Default: pipe
How to setup the child process' standard error. This can be:
'pipe'
: SetschildProcessResult.stderr
(as a string orUint8Array
) andchildProcess.stderr
(as a stream).'overlapped'
: Like'pipe'
but asynchronous on Windows.'ignore'
: Do not usestderr
.'inherit'
: Re-use the current process'stderr
.- an integer: Re-use a specific file descriptor from the current process.
- a Node.js
Writable
stream. { file: 'path' }
object.- a file URL.
- a web
WritableStream
.
This can be an array of values such as ['inherit', 'pipe']
or [filePath, 'pipe']
.
This can also be a generator function to transform the output. Learn more.
Type: string | Array<string | number | stream.Readable | stream.Writable | ReadableStream | WritableStream | URL | Uint8Array | Iterable<string> | Iterable<Uint8Array> | Iterable<unknown> | AsyncIterable<string> | AsyncIterable<Uint8Array> | AsyncIterable<unknown> | GeneratorFunction<string> | GeneratorFunction<Uint8Array> | GeneratorFunction<unknown>| AsyncGeneratorFunction<string> | AsyncGeneratorFunction<Uint8Array> | AsyncGeneratorFunction<unknown>>
(or a tuple of those types)
Default: pipe
Like the stdin
, stdout
and stderr
options but for all file descriptors at once. For example, {stdio: ['ignore', 'pipe', 'pipe']}
is the same as {stdin: 'ignore', stdout: 'pipe', stderr: 'pipe'}
.
A single string can be used as a shortcut. For example, {stdio: 'pipe'}
is the same as {stdin: 'pipe', stdout: 'pipe', stderr: 'pipe'}
.
The array can have more than 3 items, to create additional file descriptors beyond stdin
/stdout
/stderr
. For example, {stdio: ['pipe', 'pipe', 'pipe', 'pipe']}
sets a fourth file descriptor.
Type: boolean
Default: false
Add an .all
property on the promise and the resolved value. The property contains the output of the process with stdout
and stderr
interleaved.
Type: boolean
Default: false
Split stdout
and stderr
into lines.
result.stdout
,result.stderr
,result.all
andresult.stdio
are arrays of lines.childProcess.stdout
,childProcess.stderr
,childProcess.all
andchildProcess.stdio
iterate over lines instead of arbitrary chunks.- Any stream passed to the
stdout
,stderr
orstdio
option receives lines instead of arbitrary chunks.
Type: string
Default: utf8
Specify the character encoding used to decode the stdout
, stderr
and stdio
output. If set to 'buffer'
, then stdout
, stderr
and stdio
will be Uint8Array
s instead of strings.
Type: boolean
Default: true
Strip the final newline character from the output.
Type: number
Default: 100_000_000
(100 MB)
Largest amount of data in bytes allowed on stdout
, stderr
and stdio
.
Type: boolean
Default: true
if the node
option is enabled, false
otherwise
Enables exchanging messages with the child process using childProcess.send(value)
and childProcess.on('message', (value) => {})
.
Type: string
Default: 'json'
Specify the kind of serialization used for sending messages between processes when using the ipc
option:
- json
: Uses JSON.stringify()
and JSON.parse()
.
- advanced
: Uses v8.serialize()
Type: boolean
Default: false
Prepare child to run independently of its parent process. Specific behavior depends on the platform.
Type: boolean
Default: true
Kill the spawned process when the parent process exits unless either:
- the spawned process is detached
- the parent process is terminated abruptly, for example, with SIGKILL
as opposed to SIGTERM
or a normal exit
Type: number
Default: 0
If timeout
is greater than 0
, the child process will be terminated if it runs for longer than that amount of milliseconds.
Type: AbortSignal
You can abort the spawned process using AbortController
.
When AbortController.abort()
is called, .isCanceled
becomes true
.
Type: number | false
Default: 5000
If the child process is terminated but does not exit, forcefully exit it by sending SIGKILL
.
The grace period is 5 seconds by default. This feature can be disabled with false
.
This works when the child process is terminated by either:
- the
signal
,timeout
,maxBuffer
orcleanup
option - calling
subprocess.kill()
with no arguments
This does not work when the child process is terminated by either:
- calling
subprocess.kill()
with an argument - calling
process.kill(subprocess.pid)
- sending a termination signal from another process
Also, this does not work on Windows, because Windows doesn't support signals: SIGKILL
and SIGTERM
both terminate the process immediately. Other packages (such as taskkill
) can be used to achieve fail-safe termination on Windows.
Type: string | number
Default: SIGTERM
Signal used to terminate the child process when:
- using the
signal
,timeout
,maxBuffer
orcleanup
option - calling
subprocess.kill()
with no arguments
This can be either a name (like "SIGTERM"
) or a number (like 9
).
Type: string
Explicitly set the value of argv[0]
sent to the child process. This will be set to file
if not specified.
Type: number
Sets the user identity of the process.
Type: number
Sets the group identity of the process.
Type: boolean
Default: false
If true
, no quoting or escaping of arguments is done on Windows. Ignored on other platforms. This is set to true
automatically when the shell
option is true
.
Type: boolean
Default: true
On Windows, do not create a new console window. Please note this also prevents CTRL-C
from working on Windows.
The stdin
, stdout
and stderr
options can be an array of values.
The following example redirects stdout
to both the terminal and an output.txt
file, while also retrieving its value programmatically.
const {stdout} = await execa('npm', ['install'], {stdout: ['inherit', './output.txt', 'pipe']});
console.log(stdout);
When combining inherit
with other values, please note that the child process will not be an interactive TTY, even if the parent process is one.
When passing a Node.js stream to the stdin
, stdout
or stderr
option, Node.js requires that stream to have an underlying file or socket, such as the streams created by the fs
, net
or http
core modules. Otherwise the following error is thrown.
TypeError [ERR_INVALID_ARG_VALUE]: The argument 'stdio' is invalid.
This limitation can be worked around by passing either:
- a web stream (
ReadableStream
orWritableStream
) [nodeStream, 'pipe']
instead ofnodeStream
- await execa(..., {stdout: nodeStream});
+ await execa(..., {stdout: [nodeStream, 'pipe']});
Safely handle failures by using automatic retries and exponential backoff with the p-retry
package:
import pRetry from 'p-retry';
const run = async () => {
const results = await execa('curl', ['-sSL', 'https://sindresorhus.com/unicorn']);
return results;
};
console.log(await pRetry(run, {retries: 5}));
import {execa} from 'execa';
const abortController = new AbortController();
const subprocess = execa('node', [], {signal: abortController.signal});
setTimeout(() => {
abortController.abort();
}, 1000);
try {
await subprocess;
} catch (error) {
console.log(error.isTerminated); // true
console.log(error.isCanceled); // true
}
Execa can be combined with get-bin-path
to test the current package's binary. As opposed to hard-coding the path to the binary, this validates that the package.json
bin
field is correctly set up.
import {getBinPath} from 'get-bin-path';
const binPath = await getBinPath();
await execa(binPath);
The all
stream and string/Uint8Array
properties are guaranteed to interleave stdout
and stderr
.
However, for performance reasons, the child process might buffer and merge multiple simultaneous writes to stdout
or stderr
. This prevents proper interleaving.
For example, this prints 1 3 2
instead of 1 2 3
because both console.log()
are merged into a single write.
import {execa} from 'execa';
const {all} = await execa('node', ['example.js'], {all: true});
console.log(all);
// example.js
console.log('1'); // writes to stdout
console.error('2'); // writes to stderr
console.log('3'); // writes to stdout
This can be worked around by using setTimeout()
.
import {setTimeout} from 'timers/promises';
console.log('1');
console.error('2');
await setTimeout(0);
console.log('3');
- gulp-execa - Gulp plugin for Execa
- nvexeca - Run Execa using any Node.js version