Security News
GitHub Removes Malicious Pull Requests Targeting Open Source Repositories
GitHub removed 27 malicious pull requests attempting to inject harmful code across multiple open source repositories, in another round of low-effort attacks.
The execa npm package is a process execution tool that simplifies working with child processes in Node.js. It provides a better user experience than the default child_process module by offering a promise-based API, improved Windows support, and additional convenience options.
Executing a shell command
This feature allows you to execute a shell command and obtain the result. The example shows how to execute the 'echo' command and print 'unicorns' to the console.
const execa = require('execa');
(async () => {
const { stdout } = await execa('echo', ['unicorns']);
console.log(stdout);
})();
Running a command synchronously
This feature is used to execute a command synchronously, blocking the event loop until the process has finished. The example synchronously executes the 'echo' command and logs the result.
const execa = require('execa');
const { stdout } = execa.sync('echo', ['unicorns']);
console.log(stdout);
Handling errors
This feature demonstrates error handling when a command fails to execute. The example attempts to run a non-existent command and catches the error.
const execa = require('execa');
(async () => {
try {
const { stdout } = await execa('wrong-command');
console.log(stdout);
} catch (error) {
console.error('Error occurred:', error);
}
})();
Streaming output
This feature allows you to stream the output of a command directly to the console or another stream. The example streams the output of the 'echo' command to the process's stdout.
const execa = require('execa');
const subprocess = execa('echo', ['unicorns']);
subprocess.stdout.pipe(process.stdout);
ShellJS is a portable Unix shell commands implementation for Node.js. It offers a higher-level API for executing commands but does not support returning promises natively.
Cross-spawn is a cross-platform solution for spawning child processes. It aims to solve compatibility issues on Windows but does not provide a promise-based API.
Process execution for humans
One of the maintainers @ehmicky is looking for a remote full-time position as a Node.js back-end lead. Feel free to contact him!
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'
})();
Additional examples:
const execa = require('execa');
(async () => {
// Pipe the child process stdout to the current stdout
execa('echo', ['unicorns']).stdout.pipe(process.stdout);
// Catching an error
try {
await execa('wrong', ['command']);
} catch (error) {
console.log(error);
/*
{
message: 'Command failed with exit code 2 (ENOENT): wrong command spawn wrong ENOENT',
errno: 'ENOENT',
syscall: 'spawn wrong',
path: 'wrong',
spawnargs: ['command'],
command: 'wrong command',
exitCode: 2,
exitCodeName: 'ENOENT',
stdout: '',
stderr: '',
all: '',
failed: true,
timedOut: false,
isCanceled: false,
killed: false
}
*/
}
// Cancelling a spawned process
const subprocess = execa('node');
setTimeout(() => {
subprocess.cancel();
}, 1000);
try {
await subprocess;
} catch (error) {
console.log(subprocess.killed); // true
console.log(error.isCanceled); // true
}
})();
// Catching an error with a sync method
try {
execa.sync('wrong', ['command']);
} catch (error) {
console.log(error);
/*
{
message: 'Command failed with exit code 2 (ENOENT): wrong command spawnSync wrong ENOENT',
errno: 'ENOENT',
syscall: 'spawnSync wrong',
path: 'wrong',
spawnargs: ['command'],
command: 'wrong command',
exitCode: 2,
exitCodeName: 'ENOENT',
stdout: '',
stderr: '',
failed: true,
timedOut: false,
isCanceled: false,
killed: false
}
*/
}
// Kill a process with 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
.
Stream combining/interleaving stdout
and stderr
.
Execute 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.
Same as execa.command()
but synchronous.
Returns or throws a childProcessResult
.
Execute a Node.js script as a child process.
Same as execa('node', [file, ...arguments], options)
except (like child_process#fork()
):
nodePath
and nodeArguments
options can be usedshell
option cannot be usedipc
is passed to stdio
Type: object
Result of a child process execution. On success this is a plain object. On failure this is also an Error
instance.
Type: string
The file and arguments that were run.
Type: number
The numeric exit code of the process that was run.
Type: string
The textual 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
The output of the process on both stdout and stderr. undefined
if execa.sync()
was used.
Type: 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 signal that was used to terminate the process.
Type: object
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: boolean
Default: true
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: boolean
Default: true
Buffer the output from the spawned process. When buffering is disabled you must consume the output of the stdout
and stderr
streams because the promise will not be resolved/rejected until they have completed.
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: 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: 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
.
.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 string arguments passed to the Node.js executable.
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)
execa
FAQs
Process execution for humans
The npm package execa receives a total of 15,705,197 weekly downloads. As such, execa popularity was classified as popular.
We found that execa demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 2 open source maintainers collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Security News
GitHub removed 27 malicious pull requests attempting to inject harmful code across multiple open source repositories, in another round of low-effort attacks.
Security News
RubyGems.org has added a new "maintainer" role that allows for publishing new versions of gems. This new permission type is aimed at improving security for gem owners and the service overall.
Security News
Node.js will be enforcing stricter semver-major PR policies a month before major releases to enhance stability and ensure reliable release candidates.