|
|
9 months ago | |
|---|---|---|
| .. | ||
| lib | 9 months ago | |
| node_modules | 9 months ago | |
| index.d.ts | 9 months ago | |
| index.js | 9 months ago | |
| license | 9 months ago | |
| package.json | 9 months ago | |
| readme.md | 9 months ago | |
Process execution for humans
Netlify is looking for a senior/expert Node.js backend engineer to join a fully remote, international, diverse (44% women and non-binary) and friendly team. This is for the team where one of the co-maintainers @ehmicky is working. The job description is here.
This package improves child_process methods with:
stdout.trim().stdout and stderr similar to what is printed on the terminal. (Async only)$ npm install execa
const execa = require('execa');
(async () => {
const {stdout} = await execa('echo', ['unicorns']);
console.log(stdout);
//=> 'unicorns'
})();
const execa = require('execa');
execa('echo', ['unicorns']).stdout.pipe(process.stdout);
const execa = require('execa');
(async () => {
// 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',
stdout: '',
stderr: '',
all: '',
failed: true,
timedOut: false,
isCanceled: false,
killed: false
}
*/
}
})();
const execa = require('execa');
(async () => {
const subprocess = execa('node');
setTimeout(() => {
subprocess.cancel();
}, 1000);
try {
await subprocess;
} catch (error) {
console.log(subprocess.killed); // true
console.log(error.isCanceled); // true
}
})()
try {
execa.sync('unknown', ['command']);
} catch (error) {
console.log(error);
/*
{
message: 'Command failed with ENOENT: unknown command spawnSync unknown ENOENT',
errno: -2,
code: 'ENOENT',
syscall: 'spawnSync unknown',
path: 'unknown',
spawnargs: ['command'],
originalMessage: 'spawnSync unknown ENOENT',
shortMessage: 'Command failed with ENOENT: unknown command spawnSync unknown ENOENT',
command: 'unknown command',
stdout: '',
stderr: '',
all: '',
failed: true,
timedOut: false,
isCanceled: false,
killed: false
}
*/
}
Using SIGTERM, and after 2 seconds, kill it with SIGKILL.
const subprocess = execa('node');
setTimeout(() => {
subprocess.kill('SIGTERM', {
forceKillAfterTimeout: 2000
});
}, 1000);
Execute a file. Think of this as a mix of child_process.execFile() and child_process.spawn().
No escaping/quoting is needed.
Unless the shell option is used, no shell interpreter (Bash, cmd.exe, etc.) is used, so shell features such as variables substitution (echo $PATH) are not allowed.
Returns a child_process instance which:
Promise resolving or rejecting with a childProcessResult.Same as the original child_process#kill() except: if signal is SIGTERM (the default value) and the child process is not terminated after 5 seconds, force it by sending SIGKILL.
Type: number | false\
Default: 5000
Milliseconds to wait for the child process to terminate before sending SIGKILL.
Can be disabled with false.
Similar to childProcess.kill(). This is preferred when cancelling the child process execution as the error is more descriptive and childProcessResult.isCanceled is set to true.
Type: ReadableStream | undefined
Stream combining/interleaving stdout and stderr.
This is undefined if either:
all option is false (the default value)stdout and stderr options are set to 'inherit', 'ipc', Stream or integerExecute a file synchronously.
Returns or throws a childProcessResult.
Same as execa() except both file and arguments are specified in a single command string. For example, execa('echo', ['unicorns']) is the same as execa.command('echo unicorns').
If the file or an argument contains spaces, they must be escaped with backslashes. This matters especially if command is not a constant but a variable, for example with __dirname or process.cwd(). Except for spaces, no escaping/quoting is needed.
The shell option must be used if the command uses shell-specific features, as opposed to being a simple file followed by its arguments.
Same as execa.command() but synchronous.
Returns or throws a childProcessResult.
Execute a Node.js script as a child process.
Same as execa('node', [scriptPath, ...arguments], options) except (like child_process#fork()):
nodePath and nodeOptions options.shell option cannot be usedipc is passed to stdioType: 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:
0Type: string
The file and arguments that were run.
Type: number
The numeric exit code of the process that was run.
Type: string | Buffer
The output of the process on stdout.
Type: string | Buffer
The output of the process on stderr.
Type: string | Buffer | undefined
The output of the process with stdout and stderr interleaved.
This is undefined if either:
all option is false (the default value)execa.sync() was usedType: boolean
Whether the process failed to run.
Type: boolean
Whether the process timed out.
Type: boolean
Whether the process was canceled.
Type: boolean
Whether the process was killed.
Type: string | undefined
The name of the signal that was used to terminate the process. For example, SIGFPE.
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: 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 then stdout 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.
Type: string | undefined
Original error message. This is the same as the message property except it includes neither the child process stdout/stderr nor some additional information added by Execa.
This is undefined unless the child process exited due to an error event or a timeout.
Type: object
Type: boolean\
Default: true
Kill the spawned process when the parent process exits unless either:
- the spawned process is [`detached`](https://nodejs.org/api/child_process.html#child_process_options_detached)
- the parent process is terminated abruptly, for example, with `SIGKILL` as opposed to `SIGTERM` or a normal exit
Type: boolean\
Default: false
Prefer locally installed binaries when looking for a binary to execute.\
If you $ npm install foo, you can then execa('foo').
Type: string\
Default: process.cwd()
Preferred path to find locally installed binaries in (use with preferLocal).
Type: string\
Default: process.execPath (Current Node.js executable)
Path to the Node.js executable to use in child processes.
This can be either an absolute path or a path relative to the cwd option.
Requires preferLocal to be true.
For example, this can be used together with get-node to run a specific Node.js version in a child process.
Type: boolean\
Default: true
Buffer the output from the spawned process. When set to false, you must read the output of stdout and stderr (or all if the all option is true). Otherwise the returned promise will not be resolved/rejected.
If the spawned process fails, error.stdout, error.stderr, and error.all will contain the buffered data.
Type: string | Buffer | stream.Readable
Write some input to the stdin of your binary.\
Streams are not allowed when using the synchronous methods.
Type: string | number | Stream | undefined\
Default: pipe
Same options as stdio.
Type: string | number | Stream | undefined\
Default: pipe
Same options as stdio.
Type: string | number | Stream | undefined\
Default: pipe
Same options as stdio.
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: true
Setting this to false resolves the promise with the error instead of rejecting it.
Type: boolean\
Default: true
Strip the final newline character from the output.
Type: boolean\
Default: true
Set to false if you don't want to extend the environment variables when providing the env property.
Execa also accepts the below options which are the same as the options for child_process#spawn()/child_process#exec()
Type: string\
Default: process.cwd()
Current working directory of the child process.
Type: object\
Default: process.env
Environment key-value pairs. Extends automatically from process.env. Set extendEnv to false if you don't want this.
Type: string
Explicitly set the value of argv[0] sent to the child process. This will be set to file if not specified.
Type: string | string[]\
Default: pipe
Child's stdio configuration.
Type: string\
Default: 'json'
Specify the kind of serialization used for sending messages between processes when using the stdio: 'ipc' option or execa.node():
- `json`: Uses `JSON.stringify()` and `JSON.parse()`.
- `advanced`: Uses [`v8.serialize()`](https://nodejs.org/api/v8.html#v8_v8_serialize_value)
Requires Node.js 13.2.0 or later.
Type: boolean
Prepare child to run independently of its parent process. Specific behavior depends on the platform.
Type: number
Sets the user identity of the process.
Type: number
Sets the group identity of the process.
Type: boolean | string\
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:
Type: string | null\
Default: utf8
Specify the character encoding used to decode the stdout and stderr output. If set to null, then stdout and stderr will be a Buffer instead of a string.
Type: number\
Default: 0
If timeout is greater than 0, the parent will send the signal identified by the killSignal property (the default is SIGTERM) if the child runs longer than timeout milliseconds.
Type: number\
Default: 100_000_000 (100 MB)
Largest amount of data in bytes allowed on stdout or stderr.
Type: string | number\
Default: SIGTERM
Signal value to be used when the spawned process will be killed.
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.
.node() only)Type: string\
Default: process.execPath
Node.js executable used to create the child process.
.node() only)Type: string[]\
Default: process.execArgv
List of CLI options passed to the Node.js executable.
Gracefully handle failures by using automatic retries and exponential backoff with the p-retry package:
const pRetry = require('p-retry');
const run = async () => {
const results = await execa('curl', ['-sSL', 'https://sindresorhus.com/unicorn']);
return results;
};
(async () => {
console.log(await pRetry(run, {retries: 5}));
})();
Let's say you want to show the output of a child process in real-time while also saving it to a variable.
const execa = require('execa');
const subprocess = execa('echo', ['foo']);
subprocess.stdout.pipe(process.stdout);
(async () => {
const {stdout} = await subprocess;
console.log('child output:', stdout);
})();
const execa = require('execa');
const subprocess = execa('echo', ['foo'])
subprocess.stdout.pipe(fs.createWriteStream('stdout.txt'))
const execa = require('execa');
const subprocess = execa('cat')
fs.createReadStream('stdin.txt').pipe(subprocess.stdin)
const {getBinPathSync} = require('get-bin-path');
const binPath = getBinPathSync();
const subprocess = execa(binPath);
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.
execaexeca using any Node.js version