This commit is contained in:
2022-07-18 02:50:52 +00:00
parent befd344ab0
commit 06181b34d6
8569 changed files with 818704 additions and 352705 deletions
+49 -27
View File
@@ -44,7 +44,7 @@ declare namespace execa {
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`](https://github.com/ehmicky/get-node) to run a specific Node.js version in a child process.
@default process.execPath
@@ -252,10 +252,20 @@ declare namespace execa {
interface ExecaReturnBase<StdoutStderrType> {
/**
The file and arguments that were run.
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 `execa.command()`.
*/
command: string;
/**
Same as `command` but escaped.
This is meant to be copy 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 `execa.command()`.
*/
escapedCommand: string;
/**
The numeric exit code of the process that was run.
*/
@@ -334,16 +344,23 @@ declare namespace execa {
interface ExecaSyncError<StdoutErrorType = string>
extends Error,
ExecaReturnBase<StdoutErrorType> {
ExecaReturnBase<StdoutErrorType> {
/**
The error message.
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.
*/
message: string;
/**
Original error message. This is `undefined` unless the child process exited due to an `error` event or a timeout.
This is the same as the `message` property except it does not include the child process stdout/stderr.
*/
shortMessage: string;
The `message` property contains both the `originalMessage` and some additional information added by Execa.
/**
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.
*/
originalMessage?: string;
}
@@ -377,20 +394,6 @@ declare namespace execa {
}
interface ExecaChildPromise<StdoutErrorType> {
catch<ResultType = never>(
onRejected?: (reason: ExecaError<StdoutErrorType>) => ResultType | PromiseLike<ResultType>
): Promise<ExecaReturnValue<StdoutErrorType> | ResultType>;
/**
Same as the original [`child_process#kill()`](https://nodejs.org/api/child_process.html#child_process_subprocess_kill_signal), except if `signal` is `SIGTERM` (the default value) and the child process is not terminated after 5 seconds, force it by sending `SIGKILL`.
*/
kill(signal?: string, options?: execa.KillOptions): void;
/**
Similar to [`childProcess.kill()`](https://nodejs.org/api/child_process.html#child_process_subprocess_kill_signal). This is preferred when cancelling the child process execution as the error is more descriptive and [`childProcessResult.isCanceled`](#iscanceled) is set to `true`.
*/
cancel(): void;
/**
Stream combining/interleaving [`stdout`](https://nodejs.org/api/child_process.html#child_process_subprocess_stdout) and [`stderr`](https://nodejs.org/api/child_process.html#child_process_subprocess_stderr).
@@ -399,11 +402,25 @@ declare namespace execa {
- both `stdout` and `stderr` options are set to [`'inherit'`, `'ipc'`, `Stream` or `integer`](https://nodejs.org/dist/latest-v6.x/docs/api/child_process.html#child_process_options_stdio)
*/
all?: ReadableStream;
catch<ResultType = never>(
onRejected?: (reason: ExecaError<StdoutErrorType>) => ResultType | PromiseLike<ResultType>
): Promise<ExecaReturnValue<StdoutErrorType> | ResultType>;
/**
Same as the original [`child_process#kill()`](https://nodejs.org/api/child_process.html#child_process_subprocess_kill_signal), except if `signal` is `SIGTERM` (the default value) and the child process is not terminated after 5 seconds, force it by sending `SIGKILL`.
*/
kill(signal?: string, options?: KillOptions): void;
/**
Similar to [`childProcess.kill()`](https://nodejs.org/api/child_process.html#child_process_subprocess_kill_signal). This is preferred when cancelling the child process execution as the error is more descriptive and [`childProcessResult.isCanceled`](#iscanceled) is set to `true`.
*/
cancel(): void;
}
type ExecaChildProcess<StdoutErrorType = string> = ChildProcess &
ExecaChildPromise<StdoutErrorType> &
Promise<ExecaReturnValue<StdoutErrorType>>;
ExecaChildPromise<StdoutErrorType> &
Promise<ExecaReturnValue<StdoutErrorType>>;
}
declare const execa: {
@@ -418,7 +435,7 @@ declare const execa: {
@example
```
import execa from 'execa';
import execa = require('execa');
(async () => {
const {stdout} = await execa('echo', ['unicorns']);
@@ -426,8 +443,13 @@ declare const execa: {
//=> 'unicorns'
// Cancelling a spawned process
const subprocess = execa('node');
setTimeout(() => { spawned.cancel() }, 1000);
setTimeout(() => {
subprocess.cancel()
}, 1000);
try {
await subprocess;
} catch (error) {
@@ -452,7 +474,7 @@ declare const execa: {
): execa.ExecaChildProcess<Buffer>;
(file: string, options?: execa.Options): execa.ExecaChildProcess;
(file: string, options?: execa.Options<null>): execa.ExecaChildProcess<
Buffer
Buffer
>;
/**
@@ -485,14 +507,14 @@ declare const execa: {
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`.
The `shell` option must be used if the `command` uses shell-specific features (for example, `&&` or `||`), as opposed to being a simple `file` followed by its `arguments`.
@param command - The program/script to execute and its arguments.
@returns A [`child_process` instance](https://nodejs.org/api/child_process.html#child_process_class_childprocess), which is enhanced to also be a `Promise` for a result `Object` with `stdout` and `stderr` properties.
@example
```
import execa from 'execa';
import execa = require('execa');
(async () => {
const {stdout} = await execa.command('echo unicorns');
+22 -10
View File
@@ -7,10 +7,10 @@ const npmRunPath = require('npm-run-path');
const onetime = require('onetime');
const makeError = require('./lib/error');
const normalizeStdio = require('./lib/stdio');
const {spawnedKill, spawnedCancel, setupTimeout, setExitHandler} = require('./lib/kill');
const {handleInput, getSpawnedResult, makeAllStream, validateInputSync} = require('./lib/stream.js');
const {mergePromise, getSpawnedPromise} = require('./lib/promise.js');
const {joinCommand, parseCommand} = require('./lib/command.js');
const {spawnedKill, spawnedCancel, setupTimeout, validateTimeout, setExitHandler} = require('./lib/kill');
const {handleInput, getSpawnedResult, makeAllStream, validateInputSync} = require('./lib/stream');
const {mergePromise, getSpawnedPromise} = require('./lib/promise');
const {joinCommand, parseCommand, getEscapedCommand} = require('./lib/command');
const DEFAULT_MAX_BUFFER = 1000 * 1000 * 100;
@@ -24,7 +24,7 @@ const getEnv = ({env: envOption, extendEnv, preferLocal, localDir, execPath}) =>
return env;
};
const handleArgs = (file, args, options = {}) => {
const handleArguments = (file, args, options = {}) => {
const parsed = crossSpawn._parse(file, args, options);
file = parsed.command;
args = parsed.args;
@@ -72,8 +72,11 @@ const handleOutput = (options, value, error) => {
};
const execa = (file, args, options) => {
const parsed = handleArgs(file, args, options);
const parsed = handleArguments(file, args, options);
const command = joinCommand(file, args);
const escapedCommand = getEscapedCommand(file, args);
validateTimeout(parsed.options);
let spawned;
try {
@@ -87,6 +90,7 @@ const execa = (file, args, options) => {
stderr: '',
all: '',
command,
escapedCommand,
parsed,
timedOut: false,
isCanceled: false,
@@ -119,6 +123,7 @@ const execa = (file, args, options) => {
stderr,
all,
command,
escapedCommand,
parsed,
timedOut,
isCanceled: context.isCanceled,
@@ -134,6 +139,7 @@ const execa = (file, args, options) => {
return {
command,
escapedCommand,
exitCode: 0,
stdout,
stderr,
@@ -147,8 +153,6 @@ const execa = (file, args, options) => {
const handlePromiseOnce = onetime(handlePromise);
crossSpawn._enoent.hookChildProcess(spawned, parsed.parsed);
handleInput(spawned, parsed.options.input);
spawned.all = makeAllStream(spawned, parsed.options);
@@ -159,8 +163,9 @@ const execa = (file, args, options) => {
module.exports = execa;
module.exports.sync = (file, args, options) => {
const parsed = handleArgs(file, args, options);
const parsed = handleArguments(file, args, options);
const command = joinCommand(file, args);
const escapedCommand = getEscapedCommand(file, args);
validateInputSync(parsed.options);
@@ -174,6 +179,7 @@ module.exports.sync = (file, args, options) => {
stderr: '',
all: '',
command,
escapedCommand,
parsed,
timedOut: false,
isCanceled: false,
@@ -192,6 +198,7 @@ module.exports.sync = (file, args, options) => {
signal: result.signal,
exitCode: result.status,
command,
escapedCommand,
parsed,
timedOut: result.error && result.error.code === 'ETIMEDOUT',
isCanceled: false,
@@ -207,6 +214,7 @@ module.exports.sync = (file, args, options) => {
return {
command,
escapedCommand,
exitCode: 0,
stdout,
stderr,
@@ -234,8 +242,12 @@ module.exports.node = (scriptPath, args, options = {}) => {
}
const stdio = normalizeStdio.node(options);
const defaultExecArgv = process.execArgv.filter(arg => !arg.startsWith('--inspect'));
const {nodePath = process.execPath, nodeOptions = process.execArgv} = options;
const {
nodePath = process.execPath,
nodeOptions = defaultExecArgv
} = options;
return execa(
nodePath,
+34 -20
View File
@@ -1,38 +1,52 @@
'use strict';
const SPACES_REGEXP = / +/g;
const joinCommand = (file, args = []) => {
const normalizeArgs = (file, args = []) => {
if (!Array.isArray(args)) {
return file;
return [file];
}
return [file, ...args].join(' ');
return [file, ...args];
};
// Allow spaces to be escaped by a backslash if not meant as a delimiter
const handleEscaping = (tokens, token, index) => {
if (index === 0) {
return [token];
const NO_ESCAPE_REGEXP = /^[\w.-]+$/;
const DOUBLE_QUOTES_REGEXP = /"/g;
const escapeArg = arg => {
if (typeof arg !== 'string' || NO_ESCAPE_REGEXP.test(arg)) {
return arg;
}
const previousToken = tokens[tokens.length - 1];
if (previousToken.endsWith('\\')) {
return [...tokens.slice(0, -1), `${previousToken.slice(0, -1)} ${token}`];
}
return [...tokens, token];
return `"${arg.replace(DOUBLE_QUOTES_REGEXP, '\\"')}"`;
};
const joinCommand = (file, args) => {
return normalizeArgs(file, args).join(' ');
};
const getEscapedCommand = (file, args) => {
return normalizeArgs(file, args).map(arg => escapeArg(arg)).join(' ');
};
const SPACES_REGEXP = / +/g;
// Handle `execa.command()`
const parseCommand = command => {
return command
.trim()
.split(SPACES_REGEXP)
.reduce(handleEscaping, []);
const tokens = [];
for (const token of command.trim().split(SPACES_REGEXP)) {
// Allow spaces to be escaped by a backslash if not meant as a delimiter
const previousToken = tokens[tokens.length - 1];
if (previousToken && previousToken.endsWith('\\')) {
// Merge previous token with current one
tokens[tokens.length - 1] = `${previousToken.slice(0, -1)} ${token}`;
} else {
tokens.push(token);
}
}
return tokens;
};
module.exports = {
joinCommand,
getEscapedCommand,
parseCommand
};
+9 -3
View File
@@ -33,6 +33,7 @@ const makeError = ({
signal,
exitCode,
command,
escapedCommand,
timedOut,
isCanceled,
killed,
@@ -47,16 +48,21 @@ const makeError = ({
const errorCode = error && error.code;
const prefix = getErrorPrefix({timedOut, timeout, errorCode, signal, signalDescription, exitCode, isCanceled});
const message = `Command ${prefix}: ${command}`;
const execaMessage = `Command ${prefix}: ${command}`;
const isError = Object.prototype.toString.call(error) === '[object Error]';
const shortMessage = isError ? `${execaMessage}\n${error.message}` : execaMessage;
const message = [shortMessage, stderr, stdout].filter(Boolean).join('\n');
if (error instanceof Error) {
if (isError) {
error.originalMessage = error.message;
error.message = `${message}\n${error.message}`;
error.message = message;
} else {
error = new Error(message);
}
error.shortMessage = shortMessage;
error.command = command;
error.escapedCommand = escapedCommand;
error.exitCode = exitCode;
error.signal = signal;
error.signalDescription = signalDescription;
+23 -12
View File
@@ -1,7 +1,6 @@
'use strict';
const os = require('os');
const onExit = require('signal-exit');
const pFinally = require('p-finally');
const DEFAULT_FORCE_KILL_TIMEOUT = 1000 * 5;
@@ -18,9 +17,17 @@ const setKillTimeout = (kill, signal, options, killResult) => {
}
const timeout = getForceKillAfterTimeout(options);
setTimeout(() => {
const t = setTimeout(() => {
kill('SIGKILL');
}, timeout).unref();
}, timeout);
// Guarded because there's no `.unref()` when `execa` is used in the renderer
// process in Electron. This cannot be tested since we don't run tests in
// Electron.
// istanbul ignore else
if (t.unref) {
t.unref();
}
};
const shouldForceKill = (signal, {forceKillAfterTimeout}, killResult) => {
@@ -37,7 +44,7 @@ const getForceKillAfterTimeout = ({forceKillAfterTimeout = true}) => {
return DEFAULT_FORCE_KILL_TIMEOUT;
}
if (!Number.isInteger(forceKillAfterTimeout) || forceKillAfterTimeout < 0) {
if (!Number.isFinite(forceKillAfterTimeout) || forceKillAfterTimeout < 0) {
throw new TypeError(`Expected the \`forceKillAfterTimeout\` option to be a non-negative integer, got \`${forceKillAfterTimeout}\` (${typeof forceKillAfterTimeout})`);
}
@@ -64,10 +71,6 @@ const setupTimeout = (spawned, {timeout, killSignal = 'SIGTERM'}, spawnedPromise
return spawnedPromise;
}
if (!Number.isInteger(timeout) || timeout < 0) {
throw new TypeError(`Expected the \`timeout\` option to be a non-negative integer, got \`${timeout}\` (${typeof timeout})`);
}
let timeoutId;
const timeoutPromise = new Promise((resolve, reject) => {
timeoutId = setTimeout(() => {
@@ -75,15 +78,21 @@ const setupTimeout = (spawned, {timeout, killSignal = 'SIGTERM'}, spawnedPromise
}, timeout);
});
const safeSpawnedPromise = pFinally(spawnedPromise, () => {
const safeSpawnedPromise = spawnedPromise.finally(() => {
clearTimeout(timeoutId);
});
return Promise.race([timeoutPromise, safeSpawnedPromise]);
};
const validateTimeout = ({timeout}) => {
if (timeout !== undefined && (!Number.isFinite(timeout) || timeout < 0)) {
throw new TypeError(`Expected the \`timeout\` option to be a non-negative integer, got \`${timeout}\` (${typeof timeout})`);
}
};
// `cleanup` option handling
const setExitHandler = (spawned, {cleanup, detached}, timedPromise) => {
const setExitHandler = async (spawned, {cleanup, detached}, timedPromise) => {
if (!cleanup || detached) {
return timedPromise;
}
@@ -92,13 +101,15 @@ const setExitHandler = (spawned, {cleanup, detached}, timedPromise) => {
spawned.kill();
});
// TODO: Use native "finally" syntax when targeting Node.js 10
return pFinally(timedPromise, removeExitHandler);
return timedPromise.finally(() => {
removeExitHandler();
});
};
module.exports = {
spawnedKill,
spawnedCancel,
setupTimeout,
validateTimeout,
setExitHandler
};
+11 -17
View File
@@ -1,26 +1,20 @@
'use strict';
const mergePromiseProperty = (spawned, promise, property) => {
// Starting the main `promise` is deferred to avoid consuming streams
const value = typeof promise === 'function' ?
(...args) => promise()[property](...args) :
promise[property].bind(promise);
Object.defineProperty(spawned, property, {
value,
writable: true,
enumerable: false,
configurable: true
});
};
const nativePromisePrototype = (async () => {})().constructor.prototype;
const descriptors = ['then', 'catch', 'finally'].map(property => [
property,
Reflect.getOwnPropertyDescriptor(nativePromisePrototype, property)
]);
// The return value is a mixin of `childProcess` and `Promise`
const mergePromise = (spawned, promise) => {
mergePromiseProperty(spawned, promise, 'then');
mergePromiseProperty(spawned, promise, 'catch');
for (const [property, descriptor] of descriptors) {
// Starting the main `promise` is deferred to avoid consuming streams
const value = typeof promise === 'function' ?
(...args) => Reflect.apply(descriptor.value, promise(), args) :
descriptor.value.bind(promise);
// TODO: Remove the `if`-guard when targeting Node.js 10
if (Promise.prototype.finally) {
mergePromiseProperty(spawned, promise, 'finally');
Reflect.defineProperty(spawned, property, {...descriptor, value});
}
return spawned;
+8 -8
View File
@@ -1,20 +1,20 @@
'use strict';
const aliases = ['stdin', 'stdout', 'stderr'];
const hasAlias = opts => aliases.some(alias => opts[alias] !== undefined);
const hasAlias = options => aliases.some(alias => options[alias] !== undefined);
const normalizeStdio = opts => {
if (!opts) {
const normalizeStdio = options => {
if (!options) {
return;
}
const {stdio} = opts;
const {stdio} = options;
if (stdio === undefined) {
return aliases.map(alias => opts[alias]);
return aliases.map(alias => options[alias]);
}
if (hasAlias(opts)) {
if (hasAlias(options)) {
throw new Error(`It's not possible to provide \`stdio\` in combination with one of ${aliases.map(alias => `\`${alias}\``).join(', ')}`);
}
@@ -33,8 +33,8 @@ const normalizeStdio = opts => {
module.exports = normalizeStdio;
// `ipc` is pushed unless it is already present
module.exports.node = opts => {
const stdio = normalizeStdio(opts);
module.exports.node = options => {
const stdio = normalizeStdio(options);
if (stdio === 'ipc') {
return 'ipc';
+1 -1
View File
@@ -6,7 +6,7 @@ const mergeStream = require('merge-stream');
// `input` option
const handleInput = (spawned, input) => {
// Checking for stdin is workaround for https://github.com/nodejs/node/issues/26852
// TODO: Remove `|| spawned.stdin === undefined` once we drop support for Node.js <=12.2.0
// @todo remove `|| spawned.stdin === undefined` once we drop support for Node.js <=12.2.0
if (input === undefined || spawned.stdin === undefined) {
return;
}
Generated Vendored
+1 -1
View File
@@ -1,6 +1,6 @@
MIT License
Copyright (c) Sindre Sorhus <sindresorhus@gmail.com> (sindresorhus.com)
Copyright (c) Sindre Sorhus <sindresorhus@gmail.com> (https://sindresorhus.com)
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
+32 -29
View File
@@ -1,73 +1,72 @@
{
"_args": [
[
"execa@3.4.0",
"/mnt/Foxconn/Digitalent/Deverloper/liff-push_2series"
"execa@5.1.1",
"/home/node/nuxt"
]
],
"_from": "execa@3.4.0",
"_id": "execa@3.4.0",
"_from": "execa@5.1.1",
"_id": "execa@5.1.1",
"_inBundle": false,
"_integrity": "sha512-r9vdGQk4bmCuK1yKQu1KTwcT2zwfWdbdaXfCtAh+5nU/4fSX+JAb7vZGvI5naJrQlvONrEB20jeruESI69530g==",
"_integrity": "sha512-8uSpZZocAZRBAPIEINJj3Lo9HyGitllczc27Eh5YYojjMFMn8yHMDMaUHE2Jqfq05D/wucwI4JGURyXt1vchyg==",
"_location": "/execa",
"_phantomChildren": {},
"_requested": {
"type": "version",
"registry": true,
"raw": "execa@3.4.0",
"raw": "execa@5.1.1",
"name": "execa",
"escapedName": "execa",
"rawSpec": "3.4.0",
"rawSpec": "5.1.1",
"saveSpec": null,
"fetchSpec": "3.4.0"
"fetchSpec": "5.1.1"
},
"_requiredBy": [
"/@nuxt/cli"
],
"_resolved": "https://registry.npmjs.org/execa/-/execa-3.4.0.tgz",
"_spec": "3.4.0",
"_where": "/mnt/Foxconn/Digitalent/Deverloper/liff-push_2series",
"_resolved": "https://registry.npmjs.org/execa/-/execa-5.1.1.tgz",
"_spec": "5.1.1",
"_where": "/home/node/nuxt",
"author": {
"name": "Sindre Sorhus",
"email": "sindresorhus@gmail.com",
"url": "sindresorhus.com"
"url": "https://sindresorhus.com"
},
"bugs": {
"url": "https://github.com/sindresorhus/execa/issues"
},
"dependencies": {
"cross-spawn": "^7.0.0",
"get-stream": "^5.0.0",
"human-signals": "^1.1.1",
"cross-spawn": "^7.0.3",
"get-stream": "^6.0.0",
"human-signals": "^2.1.0",
"is-stream": "^2.0.0",
"merge-stream": "^2.0.0",
"npm-run-path": "^4.0.0",
"onetime": "^5.1.0",
"p-finally": "^2.0.0",
"signal-exit": "^3.0.2",
"npm-run-path": "^4.0.1",
"onetime": "^5.1.2",
"signal-exit": "^3.0.3",
"strip-final-newline": "^2.0.0"
},
"description": "Process execution for humans",
"devDependencies": {
"@types/node": "^12.0.7",
"ava": "^2.1.0",
"coveralls": "^3.0.4",
"get-node": "^5.0.0",
"@types/node": "^14.14.10",
"ava": "^2.4.0",
"get-node": "^11.0.1",
"is-running": "^2.1.0",
"nyc": "^14.1.1",
"p-event": "^4.1.0",
"nyc": "^15.1.0",
"p-event": "^4.2.0",
"tempfile": "^3.0.0",
"tsd": "^0.7.3",
"xo": "^0.24.0"
"tsd": "^0.13.1",
"xo": "^0.35.0"
},
"engines": {
"node": "^8.12.0 || >=9.7.0"
"node": ">=10"
},
"files": [
"index.js",
"index.d.ts",
"lib"
],
"funding": "https://github.com/sindresorhus/execa?sponsor=1",
"homepage": "https://github.com/sindresorhus/execa#readme",
"keywords": [
"exec",
@@ -89,6 +88,10 @@
"license": "MIT",
"name": "execa",
"nyc": {
"reporter": [
"text",
"lcov"
],
"exclude": [
"**/fixtures/**",
"**/test.js",
@@ -102,5 +105,5 @@
"scripts": {
"test": "xo && nyc ava && tsd"
},
"version": "3.4.0"
"version": "5.1.1"
}
+75 -50
View File
@@ -1,11 +1,10 @@
<img src="media/logo.svg" width="400">
<br>
[![Build Status](https://travis-ci.org/sindresorhus/execa.svg?branch=master)](https://travis-ci.org/sindresorhus/execa) [![Coverage Status](https://coveralls.io/repos/github/sindresorhus/execa/badge.svg?branch=master)](https://coveralls.io/github/sindresorhus/execa?branch=master)
[![Coverage Status](https://codecov.io/gh/sindresorhus/execa/branch/main/graph/badge.svg)](https://codecov.io/gh/sindresorhus/execa)
> Process execution for humans
## Why
This package improves [`child_process`](https://nodejs.org/api/child_process.html) methods with:
@@ -21,14 +20,12 @@ This package improves [`child_process`](https://nodejs.org/api/child_process.htm
- [Can specify file and arguments as a single string without a shell](#execacommandcommand-options)
- More descriptive errors.
## Install
```
$ npm install execa
```
## Usage
```js
@@ -63,13 +60,15 @@ const execa = require('execa');
/*
{
message: 'Command failed with ENOENT: unknown command spawn unknown ENOENT',
errno: '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: '',
all: '',
@@ -115,13 +114,15 @@ try {
/*
{
message: 'Command failed with ENOENT: unknown command spawnSync unknown ENOENT',
errno: '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',
escapedCommand: 'unknown command',
stdout: '',
stderr: '',
all: '',
@@ -148,10 +149,9 @@ setTimeout(() => {
}, 1000);
```
## API
### execa(file, arguments, [options])
### execa(file, arguments, options?)
Execute a file. Think of this as a mix of [`child_process.execFile()`](https://nodejs.org/api/child_process.html#child_process_child_process_execfile_file_args_options_callback) and [`child_process.spawn()`](https://nodejs.org/api/child_process.html#child_process_child_process_spawn_command_args_options).
@@ -163,13 +163,13 @@ Returns a [`child_process` instance](https://nodejs.org/api/child_process.html#c
- is also a `Promise` resolving or rejecting with a [`childProcessResult`](#childProcessResult).
- exposes the following additional methods and properties.
#### kill([signal], [options])
#### kill(signal?, options?)
Same as the original [`child_process#kill()`](https://nodejs.org/api/child_process.html#child_process_subprocess_kill_signal) except: if `signal` is `SIGTERM` (the default value) and the child process is not terminated after 5 seconds, force it by sending `SIGKILL`.
##### options.forceKillAfterTimeout
Type: `number | false`<br>
Type: `number | false`\
Default: `5000`
Milliseconds to wait for the child process to terminate before sending `SIGKILL`.
@@ -190,27 +190,27 @@ This is `undefined` if either:
- the [`all` option](#all-2) is `false` (the default value)
- both [`stdout`](#stdout-1) and [`stderr`](#stderr-1) options are set to [`'inherit'`, `'ipc'`, `Stream` or `integer`](https://nodejs.org/dist/latest-v6.x/docs/api/child_process.html#child_process_options_stdio)
### execa.sync(file, [arguments], [options])
### execa.sync(file, arguments?, options?)
Execute a file synchronously.
Returns or throws a [`childProcessResult`](#childProcessResult).
### execa.command(command, [options])
### execa.command(command, options?)
Same as [`execa()`](#execafile-arguments-options) 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](#shell) must be used if the `command` uses shell-specific features, as opposed to being a simple `file` followed by its `arguments`.
The [`shell` option](#shell) must be used if the `command` uses shell-specific features (for example, `&&` or `||`), as opposed to being a simple `file` followed by its `arguments`.
### execa.commandSync(command, [options])
### execa.commandSync(command, options?)
Same as [`execa.command()`](#execacommand-command-options) but synchronous.
Returns or throws a [`childProcessResult`](#childProcessResult).
### execa.node(scriptPath, [arguments], [options])
### execa.node(scriptPath, arguments?, options?)
Execute a Node.js script as a child process.
@@ -236,7 +236,18 @@ The child process [fails](#failed) when:
Type: `string`
The file and arguments that were run.
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()`](#execafile-arguments-options) or [`execa.command()`](#execacommandcommand-options).
#### escapedCommand
Type: `string`
Same as [`command`](#command) but escaped.
This is meant to be copy 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()`](#execafile-arguments-options) or [`execa.command()`](#execacommandcommand-options).
#### exitCode
@@ -306,13 +317,27 @@ A human-friendly description of the signal that was used to terminate the proces
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.
#### message
Type: `string`
Error message when the child process failed to run. In addition to the [underlying error message](#originalMessage), it also contains some information related to why the child process errored.
The child process [stderr](#stderr) then [stdout](#stdout) are appended to the end, separated with newlines and not interleaved.
#### shortMessage
Type: `string`
This is the same as the [`message` property](#message) except it does not include the child process stdout/stderr.
#### originalMessage
Type: `string | undefined`
Original error message. This is `undefined` unless the child process exited due to an `error` event or a timeout.
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.
The `message` property contains both the `originalMessage` and some additional information added by Execa.
This is `undefined` unless the child process exited due to an `error` event or a timeout.
### options
@@ -320,7 +345,7 @@ Type: `object`
#### cleanup
Type: `boolean`<br>
Type: `boolean`\
Default: `true`
Kill the spawned process when the parent process exits unless either:
@@ -329,23 +354,23 @@ Kill the spawned process when the parent process exits unless either:
#### preferLocal
Type: `boolean`<br>
Type: `boolean`\
Default: `false`
Prefer locally installed binaries when looking for a binary to execute.<br>
Prefer locally installed binaries when looking for a binary to execute.\
If you `$ npm install foo`, you can then `execa('foo')`.
#### localDir
Type: `string`<br>
Type: `string`\
Default: `process.cwd()`
Preferred path to find locally installed binaries in (use with `preferLocal`).
#### execPath
Type: `string`<br>
Default: `process.execPath` (current Node.js executable)
Type: `string`\
Default: `process.execPath` (Current Node.js executable)
Path to the Node.js executable to use in child processes.
@@ -357,7 +382,7 @@ For example, this can be used together with [`get-node`](https://github.com/ehmi
#### buffer
Type: `boolean`<br>
Type: `boolean`\
Default: `true`
Buffer the output from the spawned process. When set to `false`, you must read the output of [`stdout`](#stdout-1) and [`stderr`](#stderr-1) (or [`all`](#all) if the [`all`](#all-2) option is `true`). Otherwise the returned promise will not be resolved/rejected.
@@ -368,54 +393,54 @@ If the spawned process fails, [`error.stdout`](#stdout), [`error.stderr`](#stder
Type: `string | Buffer | stream.Readable`
Write some input to the `stdin` of your binary.<br>
Write some input to the `stdin` of your binary.\
Streams are not allowed when using the synchronous methods.
#### stdin
Type: `string | number | Stream | undefined`<br>
Type: `string | number | Stream | undefined`\
Default: `pipe`
Same options as [`stdio`](https://nodejs.org/dist/latest-v6.x/docs/api/child_process.html#child_process_options_stdio).
#### stdout
Type: `string | number | Stream | undefined`<br>
Type: `string | number | Stream | undefined`\
Default: `pipe`
Same options as [`stdio`](https://nodejs.org/dist/latest-v6.x/docs/api/child_process.html#child_process_options_stdio).
#### stderr
Type: `string | number | Stream | undefined`<br>
Type: `string | number | Stream | undefined`\
Default: `pipe`
Same options as [`stdio`](https://nodejs.org/dist/latest-v6.x/docs/api/child_process.html#child_process_options_stdio).
#### all
Type: `boolean`<br>
Type: `boolean`\
Default: `false`
Add an `.all` property on the [promise](#all) and the [resolved value](#all-1). The property contains the output of the process with `stdout` and `stderr` interleaved.
#### reject
Type: `boolean`<br>
Type: `boolean`\
Default: `true`
Setting this to `false` resolves the promise with the error instead of rejecting it.
#### stripFinalNewline
Type: `boolean`<br>
Type: `boolean`\
Default: `true`
Strip the final [newline character](https://en.wikipedia.org/wiki/Newline) from the output.
#### extendEnv
Type: `boolean`<br>
Type: `boolean`\
Default: `true`
Set to `false` if you don't want to extend the environment variables when providing the `env` property.
@@ -426,14 +451,14 @@ Execa also accepts the below options which are the same as the options for [`chi
#### cwd
Type: `string`<br>
Type: `string`\
Default: `process.cwd()`
Current working directory of the child process.
#### env
Type: `object`<br>
Type: `object`\
Default: `process.env`
Environment key-value pairs. Extends automatically from `process.env`. Set [`extendEnv`](#extendenv) to `false` if you don't want this.
@@ -446,14 +471,14 @@ Explicitly set the value of `argv[0]` sent to the child process. This will be se
#### stdio
Type: `string | string[]`<br>
Type: `string | string[]`\
Default: `pipe`
Child's [stdio](https://nodejs.org/api/child_process.html#child_process_options_stdio) configuration.
#### serialization
Type: `string`<br>
Type: `string`\
Default: `'json'`
Specify the kind of serialization used for sending messages between processes when using the [`stdio: 'ipc'`](#stdio) option or [`execa.node()`](#execanodescriptpath-arguments-options):
@@ -484,7 +509,7 @@ Sets the group identity of the process.
#### shell
Type: `boolean | string`<br>
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.
@@ -496,56 +521,56 @@ We recommend against using this option since it is:
#### encoding
Type: `string | null`<br>
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.
#### timeout
Type: `number`<br>
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.
#### maxBuffer
Type: `number`<br>
Type: `number`\
Default: `100_000_000` (100 MB)
Largest amount of data in bytes allowed on `stdout` or `stderr`.
#### killSignal
Type: `string | number`<br>
Type: `string | number`\
Default: `SIGTERM`
Signal value to be used when the spawned process will be killed.
#### windowsVerbatimArguments
Type: `boolean`<br>
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`.
#### windowsHide
Type: `boolean`<br>
Type: `boolean`\
Default: `true`
On Windows, do not create a new console window. Please note this also prevents `CTRL-C` [from working](https://github.com/nodejs/node/issues/29837) on Windows.
#### nodePath *(for `.node()` only)*
#### nodePath *(For `.node()` only)*
Type: `string`<br>
Type: `string`\
Default: [`process.execPath`](https://nodejs.org/api/process.html#process_process_execpath)
Node.js executable used to create the child process.
#### nodeOptions *(for `.node()` only)*
#### nodeOptions *(For `.node()` only)*
Type: `string[]`<br>
Type: `string[]`\
Default: [`process.execArgv`](https://nodejs.org/api/process.html#process_process_execargv)
List of [CLI options](https://nodejs.org/api/cli.html#cli_options) passed to the Node.js executable.
@@ -617,14 +642,14 @@ const subprocess = execa(binPath);
## Related
- [gulp-execa](https://github.com/ehmicky/gulp-execa) - Gulp plugin for `execa`
- [nvexeca](https://github.com/ehmicky/nvexeca) - Run `execa` using any Node.js version
- [sudo-prompt](https://github.com/jorangreef/sudo-prompt) - Run commands with elevated privileges.
## Maintainers
- [Sindre Sorhus](https://github.com/sindresorhus)
- [@ehmicky](https://github.com/ehmicky)
---
<div align="center">