Skip to content
Myr

Require Node.js 12.20 and move to ESM (#478)

Before adoption: this commit came in with the history the project adopted, so no landing records it.

authored by Minh Nguyen · committed by GitHub · parent 9216ec8 · Browse files · 62 files+1016 added−1034 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

62 files+1016 added−1034 removed

  • tests:+385 added−345 removed
  • other:+631 added−689 removed

62 files+1016 added−1034 removed

modified:.github/workflows/main.yml-1 removed
modified:lib/command.js+4 added-15 removed
modified:lib/error.js+3 added-6 removed
modified:lib/kill.js+10 added-23 removed
1'use strict';2const os = require('os');3const onExit = require('signal-exit');1import os from 'node:os';2import onExit from 'signal-exit';34const DEFAULT_FORCE_KILL_TIMEOUT = 1000 * 5;56// Monkey-patches `childProcess.kill()` to add `forceKillAfterTimeout` behavior8const spawnedKill = (kill, signal = 'SIGTERM', options = {}) => {7export const spawnedKill = (kill, signal = 'SIGTERM', options = {}) => {8 const killResult = kill(signal);9 setKillTimeout(kill, signal, options, killResult);10 return killResult;11};
16 unmodified lines
28 t.unref();29 }30};3133const shouldForceKill = (signal, {forceKillAfterTimeout}, killResult) => {34 return isSigterm(signal) && forceKillAfterTimeout !== false && killResult;35};32const shouldForceKill = (signal, {forceKillAfterTimeout}, killResult) => isSigterm(signal) && forceKillAfterTimeout !== false && killResult;3337const isSigterm = signal => {38 return signal === os.constants.signals.SIGTERM ||39 (typeof signal === 'string' && signal.toUpperCase() === 'SIGTERM');40};34const isSigterm = signal => signal === os.constants.signals.SIGTERM35 || (typeof signal === 'string' && signal.toUpperCase() === 'SIGTERM');3637const getForceKillAfterTimeout = ({forceKillAfterTimeout = true}) => {38 if (forceKillAfterTimeout === true) {39 return DEFAULT_FORCE_KILL_TIMEOUT;
6 unmodified lines
46 return forceKillAfterTimeout;47};4849// `childProcess.cancel()`55const spawnedCancel = (spawned, context) => {50export const spawnedCancel = (spawned, context) => {51 const killResult = spawned.kill();5253 if (killResult) {54 context.isCanceled = true;
5 unmodified lines
60 reject(Object.assign(new Error('Timed out'), {timedOut: true, signal}));61};6263// `timeout` option handling69const setupTimeout = (spawned, {timeout, killSignal = 'SIGTERM'}, spawnedPromise) => {64export const setupTimeout = (spawned, {timeout, killSignal = 'SIGTERM'}, spawnedPromise) => {65 if (timeout === 0 || timeout === undefined) {66 return spawnedPromise;67 }68
10 unmodified lines
7980 return Promise.race([timeoutPromise, safeSpawnedPromise]);81};8288const validateTimeout = ({timeout}) => {83export const validateTimeout = ({timeout}) => {84 if (timeout !== undefined && (!Number.isFinite(timeout) || timeout < 0)) {85 throw new TypeError(`Expected the \`timeout\` option to be a non-negative integer, got \`${timeout}\` (${typeof timeout})`);86 }87};8889// `cleanup` option handling95const setExitHandler = async (spawned, {cleanup, detached}, timedPromise) => {90export const setExitHandler = async (spawned, {cleanup, detached}, timedPromise) => {91 if (!cleanup || detached) {92 return timedPromise;93 }94
4 unmodified lines
99 return timedPromise.finally(() => {100 removeExitHandler();101 });102};108109module.exports = {110 spawnedKill,111 spawnedCancel,112 setupTimeout,113 validateTimeout,114 setExitHandler115};
modified:lib/promise.js+17 added-27 removed
1'use strict';21const nativePromisePrototype = (async () => {})().constructor.prototype;2const descriptors = ['then', 'catch', 'finally'].map(property => [3 property,6 Reflect.getOwnPropertyDescriptor(nativePromisePrototype, property)4 Reflect.getOwnPropertyDescriptor(nativePromisePrototype, property),5]);67// The return value is a mixin of `childProcess` and `Promise`10const mergePromise = (spawned, promise) => {8export const mergePromise = (spawned, promise) => {9 for (const [property, descriptor] of descriptors) {10 // Starting the main `promise` is deferred to avoid consuming streams13 const value = typeof promise === 'function' ?14 (...args) => Reflect.apply(descriptor.value, promise(), args) :15 descriptor.value.bind(promise);11 const value = typeof promise === 'function'12 ? (...args) => Reflect.apply(descriptor.value, promise(), args)13 : descriptor.value.bind(promise);1415 Reflect.defineProperty(spawned, property, {...descriptor, value});16 }1718 return spawned;19};2021// Use promises instead of `child_process` events24const getSpawnedPromise = spawned => {25 return new Promise((resolve, reject) => {26 spawned.on('exit', (exitCode, signal) => {27 resolve({exitCode, signal});28 });22export const getSpawnedPromise = spawned => new Promise((resolve, reject) => {23 spawned.on('exit', (exitCode, signal) => {24 resolve({exitCode, signal});25 });2630 spawned.on('error', error => {31 reject(error);32 });3334 if (spawned.stdin) {35 spawned.stdin.on('error', error => {36 reject(error);37 });38 }27 spawned.on('error', error => {28 reject(error);29 });40};3042module.exports = {43 mergePromise,44 getSpawnedPromise45};4631 if (spawned.stdin) {32 spawned.stdin.on('error', error => {33 reject(error);34 });35 }36});
modified:lib/stdio.js+2 added-5 removed
1'use strict';1const aliases = ['stdin', 'stdout', 'stderr'];23const hasAlias = options => aliases.some(alias => options[alias] !== undefined);46const normalizeStdio = options => {5export const normalizeStdio = options => {6 if (!options) {7 return;8 }9
18 unmodified lines
28 const length = Math.max(stdio.length, aliases.length);29 return Array.from({length}, (value, index) => stdio[index]);30};3133module.exports = normalizeStdio;3432// `ipc` is pushed unless it is already present36module.exports.node = options => {33export const normalizeStdioNode = options => {34 const stdio = normalizeStdio(options);3536 if (stdio === 'ipc') {37 return 'ipc';
12 unmodified lines
modified:lib/stream.js+8 added-17 removed
1'use strict';2const isStream = require('is-stream');3const getStream = require('get-stream');4const mergeStream = require('merge-stream');1import {isStream} from 'is-stream';2import getStream from 'get-stream';3import mergeStream from 'merge-stream';45// `input` option7const handleInput = (spawned, input) => {6export const handleInput = (spawned, input) => {7 // Checking for stdin is workaround for https://github.com/nodejs/node/issues/268528 // @todo remove `|| spawned.stdin === undefined` once we drop support for Node.js <=12.2.09 if (input === undefined || spawned.stdin === undefined) {10 return;
6 unmodified lines
17 }18};1920// `all` interleaves `stdout` and `stderr`22const makeAllStream = (spawned, {all}) => {21export const makeAllStream = (spawned, {all}) => {22 if (!all || (!spawned.stdout && !spawned.stderr)) {23 return;24 }25
37 unmodified lines
63 return getStream.buffer(stream, {maxBuffer});64};6566// Retrieve result of child process: exit code, signal, error, streams (stdout/stderr/all)68const getSpawnedResult = async ({stdout, stderr, all}, {encoding, buffer, maxBuffer}, processDone) => {67export const getSpawnedResult = async ({stdout, stderr, all}, {encoding, buffer, maxBuffer}, processDone) => {68 const stdoutPromise = getStreamPromise(stdout, {encoding, buffer, maxBuffer});69 const stderrPromise = getStreamPromise(stderr, {encoding, buffer, maxBuffer});70 const allPromise = getStreamPromise(all, {encoding, buffer, maxBuffer: maxBuffer * 2});71
3 unmodified lines
75 return Promise.all([76 {error, signal: error.signal, timedOut: error.timedOut},77 getBufferedData(stdout, stdoutPromise),78 getBufferedData(stderr, stderrPromise),80 getBufferedData(all, allPromise)79 getBufferedData(all, allPromise),80 ]);81 }82};8385const validateInputSync = ({input}) => {84export const validateInputSync = ({input}) => {85 if (isStream(input)) {86 throw new TypeError('The `input` option cannot be a stream in sync mode');87 }88};9091module.exports = {92 handleInput,93 makeAllStream,94 getSpawnedResult,95 validateInputSync96};97
deleted:test/fixtures/command with space-3 removed
1#!/usr/bin/env node2'use strict';3console.log(process.argv.slice(2).join('\n'));
added:test/fixtures/command with space.js+4 added
1#!/usr/bin/env node2import process from 'node:process';34console.log(process.argv.slice(2).join('\n'));
deleted:test/fixtures/delay-4 removed
1#!/usr/bin/env node2'use strict';34setTimeout(() => {}, Number(process.argv[2]));
added:test/fixtures/delay.js+4 added
1#!/usr/bin/env node2import process from 'node:process';34setTimeout(() => {}, Number(process.argv[2]));
deleted:test/fixtures/detach-8 removed
1#!/usr/bin/env node2'use strict';34const execa = require('../..');56const subprocess = execa('node', ['./test/fixtures/forever'], {detached: true});7console.log(subprocess.pid);8process.exit();
added:test/fixtures/detach.js+7 added
1#!/usr/bin/env node2import process from 'node:process';3import {execa} from '../../index.js';45const subprocess = execa('node', ['./test/fixtures/forever.js'], {detached: true});6console.log(subprocess.pid);7process.exit(0);
deleted:test/fixtures/echo-3 removed
1#!/usr/bin/env node2'use strict';3console.log(process.argv.slice(2).join('\n'));
deleted:test/fixtures/echo-fail-5 removed
1#!/usr/bin/env node2'use strict';3console.log('stdout');4console.error('stderr');5process.exit(1);
added:test/fixtures/echo-fail.js+6 added
1#!/usr/bin/env node2import process from 'node:process';34console.log('stdout');5console.error('stderr');6process.exit(1);
added:test/fixtures/echo.js+4 added
1#!/usr/bin/env node2import process from 'node:process';34console.log(process.argv.slice(2).join('\n'));
deleted:test/fixtures/environment-4 removed
1#!/usr/bin/env node2'use strict';3console.log(process.env.FOO);4console.log(process.env.BAR);
added:test/fixtures/environment.js+5 added
1#!/usr/bin/env node2import process from 'node:process';34console.log(process.env.FOO);5console.log(process.env.BAR);
deleted:test/fixtures/exit-3 removed
1#!/usr/bin/env node2'use strict';3process.exit(Number(process.argv[2]));
added:test/fixtures/exit.js+4 added
1#!/usr/bin/env node2import process from 'node:process';34process.exit(Number(process.argv[2]));
deleted:test/fixtures/fail-4 removed
1#!/usr/bin/env node2'use strict';34process.exit(2);
added:test/fixtures/fail.js+4 added
1#!/usr/bin/env node2import process from 'node:process';34process.exit(2);
deleted:test/fixtures/forever-4 removed
1#!/usr/bin/env node2'use strict';34setTimeout(() => {}, 1e8);
added:test/fixtures/forever.js+2 added
1#!/usr/bin/env node2setTimeout(() => {}, 1e8);
deleted:test/fixtures/max-buffer-6 removed
1#!/usr/bin/env node2'use strict';3const output = process.argv[2] || 'stdout';4const bytes = Number(process.argv[3] || 1e7);56process[output].write('.'.repeat(bytes - 1) + '\n');
added:test/fixtures/max-buffer.js+7 added
1#!/usr/bin/env node2import process from 'node:process';34const output = process.argv[2] || 'stdout';5const bytes = Number(process.argv[3] || 1e7);67process[output].write('.'.repeat(bytes - 1) + '\n');
deleted:test/fixtures/no-killable-12 removed
1#!/usr/bin/env node2'use strict';34process.on('SIGTERM', () => {5 console.log('Received SIGTERM, but we ignore it');6});78process.send('');910setInterval(() => {11 // Run forever12}, 20000);
added:test/fixtures/no-killable.js+12 added
1#!/usr/bin/env node2import process from 'node:process';34process.on('SIGTERM', () => {5 console.log('Received SIGTERM, but we ignore it');6});78process.send('');910setInterval(() => {11 // Run forever12}, 20_000);
deleted:test/fixtures/non-executable-2 removed
1#!/usr/bin/env node2'use strict';
added:test/fixtures/non-executable.js+1 added
1#!/usr/bin/env node
deleted:test/fixtures/noop-3 removed
1#!/usr/bin/env node2'use strict';3console.log(process.argv[2]);
deleted:test/fixtures/noop-132-9 removed
1#!/usr/bin/env node2'use strict';34process.stdout.write('1');5process.stderr.write('3');67setTimeout(() => {8 process.stdout.write('2');9}, 1000);
added:test/fixtures/noop-132.js+9 added
1#!/usr/bin/env node2import process from 'node:process';34process.stdout.write('1');5process.stderr.write('3');67setTimeout(() => {8 process.stdout.write('2');9}, 1000);
deleted:test/fixtures/noop-err-3 removed
1#!/usr/bin/env node2'use strict';3console.error(process.argv[2]);
added:test/fixtures/noop-err.js+4 added
1#!/usr/bin/env node2import process from 'node:process';34console.error(process.argv[2]);
deleted:test/fixtures/noop-throw-4 removed
1#!/usr/bin/env node2'use strict';3console.error(process.argv[2]);4process.exit(2);
added:test/fixtures/noop-throw.js+5 added
1#!/usr/bin/env node2import process from 'node:process';34console.error(process.argv[2]);5process.exit(2);
added:test/fixtures/noop.js+4 added
1#!/usr/bin/env node2import process from 'node:process';34console.log(process.argv[2]);
deleted:test/fixtures/send-9 removed
1#!/usr/bin/env node2'use strict';3process.on('message', message => {4 if (message === 'ping') {5 process.send('pong');6 } else {7 throw new Error('Receive wrong message');8 }9});
added:test/fixtures/send.js+12 added
1#!/usr/bin/env node2import process from 'node:process';34process.on('message', message => {5 if (message === 'ping') {6 process.send('pong');7 } else {8 throw new Error('Receive wrong message');9 }10});1112process.send('');
deleted:test/fixtures/stdin-3 removed
1#!/usr/bin/env node2'use strict';3process.stdin.pipe(process.stdout);
added:test/fixtures/stdin.js+4 added
1#!/usr/bin/env node2import process from 'node:process';34process.stdin.pipe(process.stdout);
deleted:test/fixtures/sub-process-8 removed
1#!/usr/bin/env node2'use strict';3const execa = require('../..');45const cleanup = process.argv[2] === 'true';6const detached = process.argv[3] === 'true';7const subprocess = execa('node', ['./test/fixtures/forever'], {cleanup, detached});8process.send(subprocess.pid);
deleted:test/fixtures/sub-process-exit-17 removed
1#!/usr/bin/env node2'use strict';3const execa = require('../..');45const cleanup = process.argv[2] === 'true';6const detached = process.argv[3] === 'true';78const runChild = async () => {9 try {10 await execa('node', ['./test/fixtures/noop'], {cleanup, detached});11 } catch (error) {12 console.error(error);13 process.exit(1);14 }15};1617runChild();
added:test/fixtures/sub-process-exit.js+17 added
1#!/usr/bin/env node2import process from 'node:process';3import {execa} from '../../index.js';45const cleanup = process.argv[2] === 'true';6const detached = process.argv[3] === 'true';78const runChild = async () => {9 try {10 await execa('node', ['./test/fixtures/noop.js'], {cleanup, detached});11 } catch (error) {12 console.error(error);13 process.exit(1);14 }15};1617runChild();
added:test/fixtures/sub-process.js+8 added
1#!/usr/bin/env node2import process from 'node:process';3import {execa} from '../../index.js';45const cleanup = process.argv[2] === 'true';6const detached = process.argv[3] === 'true';7const subprocess = execa('node', ['./test/fixtures/forever.js'], {cleanup, detached});8process.send(subprocess.pid);
added:test/helpers/override-promise.js+11 added
1// Can't use `test.before`, because `ava` needs `Promise`.2const nativePromise = Promise;3global.Promise = class BrokenPromise {4 then() {5 throw new Error('error');6 }7};89export function restorePromise() {10 global.Promise = nativePromise;11}
modified:test/command.js+33 added-31 removed
1import path from 'path';1import path from 'node:path';2import process from 'node:process';3import {fileURLToPath} from 'node:url';4import test from 'ava';3import execa from '..';5import {execa, execaSync, execaCommand, execaCommandSync} from '../index.js';65process.env.PATH = path.join(__dirname, 'fixtures') + path.delimiter + process.env.PATH;7process.env.PATH = fileURLToPath(new URL('./fixtures', import.meta.url)) + path.delimiter + process.env.PATH;89const command = async (t, expected, ...args) => {8 const {command: failCommand} = await t.throwsAsync(execa('fail', args));9 t.is(failCommand, `fail${expected}`);10 const {command: failCommand} = await t.throwsAsync(execa('fail.js', args));11 t.is(failCommand, `fail.js${expected}`);1211 const {command} = await execa('noop', args);12 t.is(command, `noop${expected}`);13 const {command} = await execa('noop.js', args);14 t.is(command, `noop.js${expected}`);15};1617command.title = (message, expected) => `command is: ${JSON.stringify(expected)}`;18
1 unmodified line
20test(command, ' baz quz', 'baz', 'quz');21test(command, '');2223const testEscapedCommand = async (t, expected, args) => {22 const {escapedCommand: failEscapedCommand} = await t.throwsAsync(execa('fail', args));23 t.is(failEscapedCommand, `fail ${expected}`);24 const {escapedCommand: failEscapedCommand} = await t.throwsAsync(execa('fail.js', args));25 t.is(failEscapedCommand, `fail.js ${expected}`);2627 const {escapedCommand: failEscapedCommandSync} = t.throws(() => {26 execa.sync('fail', args);28 execaSync('fail.js', args);29 });28 t.is(failEscapedCommandSync, `fail ${expected}`);30 t.is(failEscapedCommandSync, `fail.js ${expected}`);3130 const {escapedCommand} = await execa('noop', args);31 t.is(escapedCommand, `noop ${expected}`);32 const {escapedCommand} = await execa('noop.js', args);33 t.is(escapedCommand, `noop.js ${expected}`);3433 const {escapedCommand: escapedCommandSync} = execa.sync('noop', args);34 t.is(escapedCommandSync, `noop ${expected}`);35 const {escapedCommand: escapedCommandSync} = execaSync('noop.js', args);36 t.is(escapedCommandSync, `noop.js ${expected}`);37};3839testEscapedCommand.title = (message, expected) => `escapedCommand is: ${JSON.stringify(expected)}`;40
2 unmodified lines
43test(testEscapedCommand, '"\\"foo\\""', ['"foo"']);44test(testEscapedCommand, '"*"', ['*']);4546test('allow commands with spaces and no array arguments', async t => {45 const {stdout} = await execa('command with space');47 const {stdout} = await execa('command with space.js');48 t.is(stdout, '');49});5051test('allow commands with spaces and array arguments', async t => {50 const {stdout} = await execa('command with space', ['foo', 'bar']);52 const {stdout} = await execa('command with space.js', ['foo', 'bar']);53 t.is(stdout, 'foo\nbar');54});5554test('execa.command()', async t => {55 const {stdout} = await execa.command('node test/fixtures/echo foo bar');56test('execaCommand()', async t => {57 const {stdout} = await execaCommand('node test/fixtures/echo.js foo bar');58 t.is(stdout, 'foo\nbar');59});6059test('execa.command() ignores consecutive spaces', async t => {60 const {stdout} = await execa.command('node test/fixtures/echo foo bar');61test('execaCommand() ignores consecutive spaces', async t => {62 const {stdout} = await execaCommand('node test/fixtures/echo.js foo bar');63 t.is(stdout, 'foo\nbar');64});6564test('execa.command() allows escaping spaces in commands', async t => {65 const {stdout} = await execa.command('command\\ with\\ space foo bar');66test('execaCommand() allows escaping spaces in commands', async t => {67 const {stdout} = await execaCommand('command\\ with\\ space.js foo bar');68 t.is(stdout, 'foo\nbar');69});7069test('execa.command() allows escaping spaces in arguments', async t => {70 const {stdout} = await execa.command('node test/fixtures/echo foo\\ bar');71test('execaCommand() allows escaping spaces in arguments', async t => {72 const {stdout} = await execaCommand('node test/fixtures/echo.js foo\\ bar');73 t.is(stdout, 'foo bar');74});7574test('execa.command() escapes other whitespaces', async t => {75 const {stdout} = await execa.command('node test/fixtures/echo foo\tbar');76test('execaCommand() escapes other whitespaces', async t => {77 const {stdout} = await execaCommand('node test/fixtures/echo.js foo\tbar');78 t.is(stdout, 'foo\tbar');79});8079test('execa.command() trims', async t => {80 const {stdout} = await execa.command(' node test/fixtures/echo foo bar ');81test('execaCommand() trims', async t => {82 const {stdout} = await execaCommand(' node test/fixtures/echo.js foo bar ');83 t.is(stdout, 'foo\nbar');84});8584test('execa.command.sync()', t => {85 const {stdout} = execa.commandSync('node test/fixtures/echo foo bar');86test('execaCommandSync()', t => {87 const {stdout} = execaCommandSync('node test/fixtures/echo.js foo bar');88 t.is(stdout, 'foo\nbar');89});
modified:test/error.js+49 added-41 removed
1import path from 'path';2import childProcess from 'child_process';1import path from 'node:path';2import process from 'node:process';3import childProcess from 'node:child_process';4import {fileURLToPath} from 'node:url';5import {promisify} from 'node:util';6import test from 'ava';4import execa from '..';7import {execa, execaSync} from '../index.js';86process.env.PATH = path.join(__dirname, 'fixtures') + path.delimiter + process.env.PATH;9const pExec = promisify(childProcess.exec);1011process.env.PATH = fileURLToPath(new URL('./fixtures', import.meta.url)) + path.delimiter + process.env.PATH;1213const TIMEOUT_REGEXP = /timed out after/;1415const getExitRegExp = exitMessage => new RegExp(`failed with exit code ${exitMessage}`);1617test('stdout/stderr/all available on errors', async t => {13 const {stdout, stderr, all} = await t.throwsAsync(execa('exit', ['2'], {all: true}), {message: getExitRegExp('2')});18 const {stdout, stderr, all} = await t.throwsAsync(execa('exit.js', ['2'], {all: true}), {message: getExitRegExp('2')});19 t.is(typeof stdout, 'string');20 t.is(typeof stderr, 'string');21 t.is(typeof all, 'string');22});2319const WRONG_COMMAND = process.platform === 'win32' ?20 '\'wrong\' is not recognized as an internal or external command,\r\noperable program or batch file.' :21 '';24const WRONG_COMMAND = process.platform === 'win32'25 ? '\'wrong\' is not recognized as an internal or external command,\r\noperable program or batch file.'26 : '';2728test('stdout/stderr/all on process errors', async t => {29 const {stdout, stderr, all} = await t.throwsAsync(execa('wrong command', {all: true}));30 t.is(stdout, '');
2 unmodified lines
33});3435test('stdout/stderr/all on process errors, in sync mode', t => {36 const {stdout, stderr, all} = t.throws(() => {32 execa.sync('wrong command');37 execaSync('wrong command');38 });39 t.is(stdout, '');40 t.is(stderr, WRONG_COMMAND);41 t.is(all, undefined);42});4344test('exitCode is 0 on success', async t => {40 const {exitCode} = await execa('noop', ['foo']);45 const {exitCode} = await execa('noop.js', ['foo']);46 t.is(exitCode, 0);47});4849const testExitCode = async (t, number) => {45 const {exitCode} = await t.throwsAsync(execa('exit', [`${number}`]), {message: getExitRegExp(number)});50 const {exitCode} = await t.throwsAsync(execa('exit.js', [`${number}`]), {message: getExitRegExp(number)});51 t.is(exitCode, number);52};5354test('exitCode is 2', testExitCode, 2);55test('exitCode is 3', testExitCode, 3);56test('exitCode is 4', testExitCode, 4);5758test('error.message contains the command', async t => {54 await t.throwsAsync(execa('exit', ['2', 'foo', 'bar']), {message: /exit 2 foo bar/});59 await t.throwsAsync(execa('exit.js', ['2', 'foo', 'bar']), {message: /exit.js 2 foo bar/});60});6162test('error.message contains stdout/stderr if available', async t => {58 const {message} = await t.throwsAsync(execa('echo-fail'));63 const {message} = await t.throwsAsync(execa('echo-fail.js'));64 t.true(message.includes('stderr'));65 t.true(message.includes('stdout'));66});6768test('error.message does not contain stdout/stderr if not available', async t => {64 const {message} = await t.throwsAsync(execa('echo-fail', {stdio: 'ignore'}));69 const {message} = await t.throwsAsync(execa('echo-fail.js', {stdio: 'ignore'}));70 t.false(message.includes('stderr'));71 t.false(message.includes('stdout'));72});7374test('error.shortMessage does not contain stdout/stderr', async t => {70 const {shortMessage} = await t.throwsAsync(execa('echo-fail'));75 const {shortMessage} = await t.throwsAsync(execa('echo-fail.js'));76 t.false(shortMessage.includes('stderr'));77 t.false(shortMessage.includes('stdout'));78});7980test('Original error.message is kept', async t => {76 const {originalMessage} = await t.throwsAsync(execa('noop', {cwd: 1}));77 t.true(originalMessage.startsWith('The "options.cwd" property must be of type string. Received type number'));81 const {originalMessage} = await t.throwsAsync(execa('noop.js', {cwd: 1}));82 // On Node >=14.18.0, the error message is83 // `The "options.cwd" property must be of type string or an instance of Buffer or URL. Received type number (1)`84 t.true(originalMessage.startsWith('The "options.cwd" property must be of type string'));85 t.true(originalMessage.includes('. Received type number'));86});8788test('failed is false on success', async t => {81 const {failed} = await execa('noop', ['foo']);89 const {failed} = await execa('noop.js', ['foo']);90 t.false(failed);91});9293test('failed is true on failure', async t => {86 const {failed} = await t.throwsAsync(execa('exit', ['2']));94 const {failed} = await t.throwsAsync(execa('exit.js', ['2']));95 t.true(failed);96});9798test('error.killed is true if process was killed directly', async t => {91 const subprocess = execa('noop');99 const subprocess = execa('noop.js');100101 subprocess.kill();102103 const {killed} = await t.throwsAsync(subprocess, {message: /was killed with SIGTERM/});104 t.true(killed);105});106107test('error.killed is false if process was killed indirectly', async t => {100 const subprocess = execa('noop');108 const subprocess = execa('noop.js');109110 process.kill(subprocess.pid, 'SIGINT');111112 // `process.kill()` is emulated by Node.js on Windows
2 unmodified lines
115 t.false(killed);116});117118test('result.killed is false if not killed', async t => {111 const {killed} = await execa('noop');119 const {killed} = await execa('noop.js');120 t.false(killed);121});122123test('result.killed is false if not killed, in sync mode', t => {116 const {killed} = execa.sync('noop');124 const {killed} = execaSync('noop.js');125 t.false(killed);126});127128test('result.killed is false on process error', async t => {
2 unmodified lines
131});132133test('result.killed is false on process error, in sync mode', t => {134 const {killed} = t.throws(() => {127 execa.sync('wrong command');135 execaSync('wrong command');136 });137 t.false(killed);138});139140if (process.platform === 'darwin') {133 test.cb('sanity check: child_process.exec also has killed.false if killed indirectly', t => {134 const {pid} = childProcess.exec('noop', error => {135 t.truthy(error);136 t.false(error.killed);137 t.end();138 });141 test('sanity check: child_process.exec also has killed.false if killed indirectly', async t => {142 const promise = pExec('noop.js');143140 process.kill(pid, 'SIGINT');144 process.kill(promise.child.pid, 'SIGINT');145146 const error = await t.throwsAsync(promise);147 t.truthy(error);148 t.false(error.killed);149 });150}151152if (process.platform !== 'win32') {153 test('error.signal is SIGINT', async t => {146 const subprocess = execa('noop');154 const subprocess = execa('noop.js');155156 process.kill(subprocess.pid, 'SIGINT');157158 const {signal} = await t.throwsAsync(subprocess, {message: /was killed with SIGINT/});159 t.is(signal, 'SIGINT');160 });161162 test('error.signalDescription is defined', async t => {155 const subprocess = execa('noop');163 const subprocess = execa('noop.js');164165 process.kill(subprocess.pid, 'SIGINT');166167 const {signalDescription} = await t.throwsAsync(subprocess, {message: /User interruption with CTRL-C/});168 t.is(signalDescription, 'User interruption with CTRL-C');169 });170171 test('error.signal is SIGTERM', async t => {164 const subprocess = execa('noop');172 const subprocess = execa('noop.js');173174 process.kill(subprocess.pid, 'SIGTERM');175176 const {signal} = await t.throwsAsync(subprocess, {message: /was killed with SIGTERM/});177 t.is(signal, 'SIGTERM');178 });179180 test('custom error.signal', async t => {173 const {signal} = await t.throwsAsync(execa('noop', {killSignal: 'SIGHUP', timeout: 1, message: TIMEOUT_REGEXP}));181 const {signal} = await t.throwsAsync(execa('noop.js', {killSignal: 'SIGHUP', timeout: 1, message: TIMEOUT_REGEXP}));182 t.is(signal, 'SIGHUP');183 });184185 test('exitCode is undefined on signal termination', async t => {178 const subprocess = execa('noop');186 const subprocess = execa('noop.js');187188 process.kill(subprocess.pid);189190 const {exitCode} = await t.throwsAsync(subprocess);
1 unmodified line
192 });193}194195test('result.signal is undefined for successful execution', async t => {188 const {signal} = await execa('noop');196 const {signal} = await execa('noop.js');197 t.is(signal, undefined);198});199200test('result.signal is undefined if process failed, but was not killed', async t => {193 const {signal} = await t.throwsAsync(execa('exit', [2]), {message: getExitRegExp('2')});201 const {signal} = await t.throwsAsync(execa('exit.js', [2]), {message: getExitRegExp('2')});202 t.is(signal, undefined);203});204205test('result.signalDescription is undefined for successful execution', async t => {198 const {signalDescription} = await execa('noop');206 const {signalDescription} = await execa('noop.js');207 t.is(signalDescription, undefined);208});209210test('error.code is undefined on success', async t => {203 const {code} = await execa('noop');211 const {code} = await execa('noop.js');212 t.is(code, undefined);213});214215test('error.code is defined on failure if applicable', async t => {208 const {code} = await t.throwsAsync(execa('noop', {cwd: 1}));216 const {code} = await t.throwsAsync(execa('noop.js', {cwd: 1}));217 t.is(code, 'ERR_INVALID_ARG_TYPE');218});
modified:test/kill.js+36 added-34 removed
1import path from 'path';1import path from 'node:path';2import process from 'node:process';3import {fileURLToPath} from 'node:url';4import test from 'ava';5import pEvent from 'p-event';6import isRunning from 'is-running';5import execa from '..';7import {execa, execaSync} from '../index.js';87process.env.PATH = path.join(__dirname, 'fixtures') + path.delimiter + process.env.PATH;9process.env.PATH = fileURLToPath(new URL('./fixtures', import.meta.url)) + path.delimiter + process.env.PATH;1011const TIMEOUT_REGEXP = /timed out after/;1213test('kill("SIGKILL") should terminate cleanly', async t => {12 const subprocess = execa('node', ['./test/fixtures/no-killable'], {stdio: ['ipc']});14 const subprocess = execa('node', ['./test/fixtures/no-killable.js'], {stdio: ['ipc']});15 await pEvent(subprocess, 'message');1617 subprocess.kill('SIGKILL');18
4 unmodified lines
23// `SIGTERM` cannot be caught on Windows, and it always aborts the process (like `SIGKILL` on Unix).24// Therefore, this feature and those tests do not make sense on Windows.25if (process.platform !== 'win32') {26 test('`forceKillAfterTimeout: false` should not kill after a timeout', async t => {25 const subprocess = execa('node', ['./test/fixtures/no-killable'], {stdio: ['ipc']});27 const subprocess = execa('node', ['./test/fixtures/no-killable.js'], {stdio: ['ipc']});28 await pEvent(subprocess, 'message');2930 subprocess.kill('SIGTERM', {forceKillAfterTimeout: false});31
1 unmodified line
33 subprocess.kill('SIGKILL');34 });3536 test('`forceKillAfterTimeout: number` should kill after a timeout', async t => {35 const subprocess = execa('node', ['./test/fixtures/no-killable'], {stdio: ['ipc']});37 const subprocess = execa('node', ['./test/fixtures/no-killable.js'], {stdio: ['ipc']});38 await pEvent(subprocess, 'message');3940 subprocess.kill('SIGTERM', {forceKillAfterTimeout: 50});41
1 unmodified line
43 t.is(signal, 'SIGKILL');44 });4546 test('`forceKillAfterTimeout: true` should kill after a timeout', async t => {45 const subprocess = execa('node', ['./test/fixtures/no-killable'], {stdio: ['ipc']});47 const subprocess = execa('node', ['./test/fixtures/no-killable.js'], {stdio: ['ipc']});48 await pEvent(subprocess, 'message');4950 subprocess.kill('SIGTERM', {forceKillAfterTimeout: true});51
1 unmodified line
53 t.is(signal, 'SIGKILL');54 });5556 test('kill() with no arguments should kill after a timeout', async t => {55 const subprocess = execa('node', ['./test/fixtures/no-killable'], {stdio: ['ipc']});57 const subprocess = execa('node', ['./test/fixtures/no-killable.js'], {stdio: ['ipc']});58 await pEvent(subprocess, 'message');5960 subprocess.kill();61
2 unmodified lines
64 });6566 test('`forceKillAfterTimeout` should not be NaN', t => {67 t.throws(() => {66 execa('noop').kill('SIGTERM', {forceKillAfterTimeout: Number.NaN});68 execa('noop.js').kill('SIGTERM', {forceKillAfterTimeout: Number.NaN});69 }, {instanceOf: TypeError, message: /non-negative integer/});70 });7172 test('`forceKillAfterTimeout` should not be negative', t => {73 t.throws(() => {72 execa('noop').kill('SIGTERM', {forceKillAfterTimeout: -1});74 execa('noop.js').kill('SIGTERM', {forceKillAfterTimeout: -1});75 }, {instanceOf: TypeError, message: /non-negative integer/});76 });77}7879test('execa() returns a promise with kill()', t => {78 const {kill} = execa('noop', ['foo']);80 const {kill} = execa('noop.js', ['foo']);81 t.is(typeof kill, 'function');82});8384test('timeout kills the process if it times out', async t => {83 const {killed, timedOut} = await t.throwsAsync(execa('noop', {timeout: 1}), TIMEOUT_REGEXP);85 const {killed, timedOut} = await t.throwsAsync(execa('noop.js', {timeout: 1}), {message: TIMEOUT_REGEXP});86 t.false(killed);87 t.true(timedOut);88});8990test('timeout kills the process if it times out, in sync mode', async t => {91 const {killed, timedOut} = await t.throws(() => {90 execa.sync('noop', {timeout: 1, message: TIMEOUT_REGEXP});92 execaSync('noop.js', {timeout: 1, message: TIMEOUT_REGEXP});93 });94 t.false(killed);95 t.true(timedOut);96});9798test('timeout does not kill the process if it does not time out', async t => {97 const {timedOut} = await execa('delay', ['500'], {timeout: 1e8});99 const {timedOut} = await execa('delay.js', ['500'], {timeout: 1e8});100 t.false(timedOut);101});102103const INVALID_TIMEOUT_REGEXP = /`timeout` option to be a non-negative integer/;104105test('timeout must not be negative', async t => {106 await t.throws(() => {105 execa('noop', {timeout: -1});106 }, INVALID_TIMEOUT_REGEXP);107 execa('noop.js', {timeout: -1});108 }, {message: INVALID_TIMEOUT_REGEXP});109});110111test('timeout must be an integer', async t => {112 await t.throws(() => {111 execa('noop', {timeout: false});112 }, INVALID_TIMEOUT_REGEXP);113 execa('noop.js', {timeout: false});114 }, {message: INVALID_TIMEOUT_REGEXP});115});116117test('timedOut is false if timeout is undefined', async t => {116 const {timedOut} = await execa('noop');118 const {timedOut} = await execa('noop.js');119 t.false(timedOut);120});121122test('timedOut is false if timeout is 0', async t => {121 const {timedOut} = await execa('noop', {timeout: 0});123 const {timedOut} = await execa('noop.js', {timeout: 0});124 t.false(timedOut);125});126127test('timedOut is false if timeout is undefined and exit code is 0 in sync mode', t => {126 const {timedOut} = execa.sync('noop');128 const {timedOut} = execaSync('noop.js');129 t.false(timedOut);130});131132// When child process exits before parent process133const spawnAndExit = async (t, cleanup, detached) => {132 await t.notThrowsAsync(execa('sub-process-exit', [cleanup, detached]));134 await t.notThrowsAsync(execa('sub-process-exit.js', [cleanup, detached]));135};136137test('spawnAndExit', spawnAndExit, false, false);138test('spawnAndExit cleanup', spawnAndExit, true, false);
1 unmodified line
140test('spawnAndExit cleanup detached', spawnAndExit, true, true);141142// When parent process exits before child process143const spawnAndKill = async (t, [signal, cleanup, detached, isKilled]) => {142 const subprocess = execa('sub-process', [cleanup, detached], {stdio: ['ignore', 'ignore', 'ignore', 'ipc']});144 const subprocess = execa('sub-process.js', [cleanup, detached], {stdio: ['ignore', 'ignore', 'ignore', 'ipc']});145146 const pid = await pEvent(subprocess, 'message');147 t.true(Number.isInteger(pid));148 t.true(isRunning(pid));
30 unmodified lines
179test('removes exit handler on exit', async t => {180 // @todo this relies on `signal-exit` internals181 const emitter = process.__signal_exit_emitter__;182181 const subprocess = execa('noop');183 const subprocess = execa('noop.js');184 const listener = emitter.listeners('exit').pop();185186 await new Promise((resolve, reject) => {187 subprocess.on('error', reject);
10 unmodified lines
198 t.true(subprocess.killed);199});200201test('result.isCanceled is false when spawned.cancel() isn\'t called (success)', async t => {200 const {isCanceled} = await execa('noop');202 const {isCanceled} = await execa('noop.js');203 t.false(isCanceled);204});205206test('result.isCanceled is false when spawned.cancel() isn\'t called (failure)', async t => {205 const {isCanceled} = await t.throwsAsync(execa('fail'));207 const {isCanceled} = await t.throwsAsync(execa('fail.js'));208 t.false(isCanceled);209});210211test('result.isCanceled is false when spawned.cancel() isn\'t called in sync mode (success)', t => {210 const {isCanceled} = execa.sync('noop');212 const {isCanceled} = execaSync('noop.js');213 t.false(isCanceled);214});215216test('result.isCanceled is false when spawned.cancel() isn\'t called in sync mode (failure)', t => {217 const {isCanceled} = t.throws(() => {216 execa.sync('fail');218 execaSync('fail.js');219 });220 t.false(isCanceled);221});222223test('calling cancel method throws an error with message "Command was canceled"', async t => {222 const subprocess = execa('noop');224 const subprocess = execa('noop.js');225 subprocess.cancel();226 await t.throwsAsync(subprocess, {message: /Command was canceled/});227});228229test('error.isCanceled is true when cancel method is used', async t => {228 const subprocess = execa('noop');230 const subprocess = execa('noop.js');231 subprocess.cancel();232 const {isCanceled} = await t.throwsAsync(subprocess);233 t.true(isCanceled);234});235236test('error.isCanceled is false when kill method is used', async t => {235 const subprocess = execa('noop');237 const subprocess = execa('noop.js');238 subprocess.kill();239 const {isCanceled} = await t.throwsAsync(subprocess);240 t.false(isCanceled);241});242243test('calling cancel method twice should show the same behaviour as calling it once', async t => {242 const subprocess = execa('noop');244 const subprocess = execa('noop.js');245 subprocess.cancel();246 subprocess.cancel();247 const {isCanceled} = await t.throwsAsync(subprocess);248 t.true(isCanceled);249 t.true(subprocess.killed);250});251252test('calling cancel method on a successfully completed process does not make result.isCanceled true', async t => {251 const subprocess = execa('noop');253 const subprocess = execa('noop.js');254 const {isCanceled} = await subprocess;255 subprocess.cancel();256 t.false(isCanceled);257});258259test('calling cancel method on a process which has been killed does not make error.isCanceled true', async t => {258 const subprocess = execa('noop');260 const subprocess = execa('noop.js');261 subprocess.kill();262 const {isCanceled} = await t.throwsAsync(subprocess);263 t.false(isCanceled);264});
modified:test/node.js+24 added-20 removed
1import path from 'path';1import path from 'node:path';2import process from 'node:process';3import {fileURLToPath} from 'node:url';4import test from 'ava';5import pEvent from 'p-event';4import execa from '..';6import {execaNode} from '../index.js';76process.env.PATH = path.join(__dirname, 'fixtures') + path.delimiter + process.env.PATH;8process.env.PATH = fileURLToPath(new URL('./fixtures', import.meta.url)) + path.delimiter + process.env.PATH;910async function inspectMacro(t, input) {11 const originalArgv = process.execArgv;12 process.execArgv = [input, '-e'];13 try {12 const subprocess = execa.node('console.log("foo")', {13 reject: false14 const subprocess = execaNode('console.log("foo")', {15 reject: false,16 });1718 const {stdout, stderr} = await subprocess;19
4 unmodified lines
24 }25}2627test('node()', async t => {26 const {exitCode} = await execa.node('test/fixtures/noop');28 const {exitCode} = await execaNode('test/fixtures/noop.js');29 t.is(exitCode, 0);30});3132test('node pipe stdout', async t => {31 const {stdout} = await execa.node('test/fixtures/noop', ['foo'], {32 stdout: 'pipe'33 const {stdout} = await execaNode('test/fixtures/noop.js', ['foo'], {34 stdout: 'pipe',35 });3637 t.is(stdout, 'foo');38});3940test('node correctly use nodePath', async t => {39 const {stdout} = await execa.node(process.platform === 'win32' ? 'hello.cmd' : 'hello.sh', {41 const {stdout} = await execaNode(process.platform === 'win32' ? 'hello.cmd' : 'hello.sh', {42 stdout: 'pipe',43 nodePath: process.platform === 'win32' ? 'cmd.exe' : 'bash',42 nodeOptions: process.platform === 'win32' ? ['/c'] : []44 nodeOptions: process.platform === 'win32' ? ['/c'] : [],45 });4647 t.is(stdout, 'Hello World');48});4950test('node pass on nodeOptions', async t => {49 const {stdout} = await execa.node('console.log("foo")', {51 const {stdout} = await execaNode('console.log("foo")', {52 stdout: 'pipe',51 nodeOptions: ['-e']53 nodeOptions: ['-e'],54 });5556 t.is(stdout, 'foo');57});5859test.serial(60 'node removes --inspect from nodeOptions when defined by parent process',61 inspectMacro,60 '--inspect'62 '--inspect',63);6465test.serial(66 'node removes --inspect=9222 from nodeOptions when defined by parent process',67 inspectMacro,66 '--inspect=9222'68 '--inspect=9222',69);7071test.serial(72 'node removes --inspect-brk from nodeOptions when defined by parent process',73 inspectMacro,72 '--inspect-brk'74 '--inspect-brk',75);7677test.serial(78 'node removes --inspect-brk=9222 from nodeOptions when defined by parent process',79 inspectMacro,78 '--inspect-brk=9222'80 '--inspect-brk=9222',81);8283test.serial(84 'node should not remove --inspect when passed through nodeOptions',85 async t => {84 const {stdout, stderr} = await execa.node('console.log("foo")', {86 const {stdout, stderr} = await execaNode('console.log("foo")', {87 reject: false,86 nodeOptions: ['--inspect', '-e']88 nodeOptions: ['--inspect', '-e'],89 });9091 t.is(stdout, 'foo');92 t.true(stderr.includes('Debugger listening'));91 }93 },94);9596test('node\'s forked script has a communication channel', async t => {95 const subprocess = execa.node('test/fixtures/send');97 const subprocess = execaNode('test/fixtures/send.js');98 await pEvent(subprocess, 'message');99100 subprocess.send('ping');101102 const message = await pEvent(subprocess, 'message');103 t.is(message, 'pong');
1 unmodified line
modified:test/override-promise.js+11 added-13 removed
1import path from 'path';1import path from 'node:path';2import process from 'node:process';3import {fileURLToPath} from 'node:url';4import test from 'ava';5// The helper module overrides Promise on import so has to be imported before `execa`.6// Can't use top-level await (TLA) + `import(…)` since Node.js 12 doesn't support TLA.7import {restorePromise} from './helpers/override-promise.js';8// eslint-disable-next-line import/order9import {execa} from '../index.js';104process.env.PATH = path.join(__dirname, 'fixtures') + path.delimiter + process.env.PATH;11restorePromise();126// Can't use `test.before`, because `ava` needs `Promise`.7// Can't use `import(…)` either, because `execa` is not an ES Module.8const nativePromise = Promise;9global.Promise = class BrokenPromise {10 then() {11 throw new Error('error');12 }13};14const execa = require('..');15global.Promise = nativePromise;13process.env.PATH = fileURLToPath(new URL('./fixtures', import.meta.url)) + path.delimiter + process.env.PATH;1415test('should work with third-party Promise', async t => {18 const {stdout} = await execa('noop', ['foo']);16 const {stdout} = await execa('noop.js', ['foo']);17 t.is(stdout, 'foo');18});
modified:test/promise.js+10 added-9 removed
1import path from 'path';1import path from 'node:path';2import process from 'node:process';3import {fileURLToPath} from 'node:url';4import test from 'ava';3import execa from '..';5import {execa} from '../index.js';65process.env.PATH = path.join(__dirname, 'fixtures') + path.delimiter + process.env.PATH;7process.env.PATH = fileURLToPath(new URL('./fixtures', import.meta.url)) + path.delimiter + process.env.PATH;89test('promise methods are not enumerable', t => {8 const descriptors = Object.getOwnPropertyDescriptors(execa('noop'));9 // eslint-disable-next-line promise/prefer-await-to-then10 const descriptors = Object.getOwnPropertyDescriptors(execa('noop.js'));11 t.false(descriptors.then.enumerable);12 t.false(descriptors.catch.enumerable);13 t.false(descriptors.finally.enumerable);14});1516test('finally function is executed on success', async t => {17 let isCalled = false;17 const {stdout} = await execa('noop', ['foo']).finally(() => {18 const {stdout} = await execa('noop.js', ['foo']).finally(() => {19 isCalled = true;20 });21 t.is(isCalled, true);22 t.is(stdout, 'foo');23});2425test('finally function is executed on failure', async t => {26 let isError = false;26 const {stdout, stderr} = await t.throwsAsync(execa('exit', ['2']).finally(() => {27 const {stdout, stderr} = await t.throwsAsync(execa('exit.js', ['2']).finally(() => {28 isError = true;29 }));30 t.is(isError, true);31 t.is(typeof stdout, 'string');32 t.is(typeof stderr, 'string');33});3435test('throw in finally function bubbles up on success', async t => {35 const {message} = await t.throwsAsync(execa('noop', ['foo']).finally(() => {36 const {message} = await t.throwsAsync(execa('noop.js', ['foo']).finally(() => {37 throw new Error('called');38 }));39 t.is(message, 'called');40});4142test('throw in finally bubbles up on error', async t => {42 const {message} = await t.throwsAsync(execa('exit', ['2']).finally(() => {43 const {message} = await t.throwsAsync(execa('exit.js', ['2']).finally(() => {44 throw new Error('called');45 }));46 t.is(message, 'called');47});
modified:test/stdio.js+5 added-5 removed
1import {inspect} from 'util';1import {inspect} from 'node:util';2import test from 'ava';3import normalizeStdio from '../lib/stdio';3import {normalizeStdio, normalizeStdioNode} from '../lib/stdio.js';45const macro = (t, input, expected, func) => {6 if (expected instanceof Error) {7 t.throws(() => {8 normalizeStdio(input);9 }, expected.message);9 }, {message: expected.message});10 return;11 }1213 t.deepEqual(func(input), expected);
32 unmodified lines
46test(stdioMacro, {stdin: 'inherit', stdio: ['pipe']}, new Error('It\'s not possible to provide `stdio` in combination with one of `stdin`, `stdout`, `stderr`'));47test(stdioMacro, {stdin: 'inherit', stdio: [undefined, 'pipe']}, new Error('It\'s not possible to provide `stdio` in combination with one of `stdin`, `stdout`, `stderr`'));48test(stdioMacro, {stdin: 0, stdio: 'pipe'}, new Error('It\'s not possible to provide `stdio` in combination with one of `stdin`, `stdout`, `stderr`'));4950const forkMacro = (...args) => macro(...args, normalizeStdio.node);51forkMacro.title = macroTitle('execa.fork()');50const forkMacro = (...args) => macro(...args, normalizeStdioNode);51forkMacro.title = macroTitle('execaNode()');5253test(forkMacro, undefined, [undefined, undefined, undefined, 'ipc']);54test(forkMacro, {stdio: 'ignore'}, ['ignore', 'ignore', 'ignore', 'ipc']);55test(forkMacro, {stdio: 'ipc'}, 'ipc');
11 unmodified lines
modified:test/stream.js+43 added-40 removed
1import path from 'path';2import fs from 'fs';3import Stream from 'stream';1import {Buffer} from 'node:buffer';2import path from 'node:path';3import process from 'node:process';4import fs from 'node:fs';5import {fileURLToPath} from 'node:url';6import Stream from 'node:stream';7import test from 'ava';8import getStream from 'get-stream';9import tempfile from 'tempfile';7import execa from '..';10import {execa, execaSync} from '../index.js';119process.env.PATH = path.join(__dirname, 'fixtures') + path.delimiter + process.env.PATH;12process.env.PATH = fileURLToPath(new URL('./fixtures', import.meta.url)) + path.delimiter + process.env.PATH;1314test('buffer', async t => {12 const {stdout} = await execa('noop', ['foo'], {encoding: null});15 const {stdout} = await execa('noop.js', ['foo'], {encoding: null});16 t.true(Buffer.isBuffer(stdout));17 t.is(stdout.toString(), 'foo');18});1920test('pass `stdout` to a file descriptor', async t => {21 const file = tempfile('.txt');19 await execa('test/fixtures/noop', ['foo bar'], {stdout: fs.openSync(file, 'w')});22 await execa('test/fixtures/noop.js', ['foo bar'], {stdout: fs.openSync(file, 'w')});23 t.is(fs.readFileSync(file, 'utf8'), 'foo bar\n');24});2526test('pass `stderr` to a file descriptor', async t => {27 const file = tempfile('.txt');25 await execa('test/fixtures/noop-err', ['foo bar'], {stderr: fs.openSync(file, 'w')});28 await execa('test/fixtures/noop-err.js', ['foo bar'], {stderr: fs.openSync(file, 'w')});29 t.is(fs.readFileSync(file, 'utf8'), 'foo bar\n');30});3132test.serial('result.all shows both `stdout` and `stderr` intermixed', async t => {30 const {all} = await execa('noop-132', {all: true});33 const {all} = await execa('noop-132.js', {all: true});34 t.is(all, '132');35});3637test('result.all is undefined unless opts.all is true', async t => {35 const {all} = await execa('noop');38 const {all} = await execa('noop.js');39 t.is(all, undefined);40});4142test('stdout/stderr/all are undefined if ignored', async t => {40 const {stdout, stderr, all} = await execa('noop', {stdio: 'ignore', all: true});43 const {stdout, stderr, all} = await execa('noop.js', {stdio: 'ignore', all: true});44 t.is(stdout, undefined);45 t.is(stderr, undefined);46 t.is(all, undefined);47});4849test('stdout/stderr/all are undefined if ignored in sync mode', t => {47 const {stdout, stderr, all} = execa.sync('noop', {stdio: 'ignore', all: true});50 const {stdout, stderr, all} = execaSync('noop.js', {stdio: 'ignore', all: true});51 t.is(stdout, undefined);52 t.is(stderr, undefined);53 t.is(all, undefined);54});5556test('input option can be a String', async t => {54 const {stdout} = await execa('stdin', {input: 'foobar'});57 const {stdout} = await execa('stdin.js', {input: 'foobar'});58 t.is(stdout, 'foobar');59});6061test('input option can be a Buffer', async t => {59 const {stdout} = await execa('stdin', {input: 'testing12'});62 const {stdout} = await execa('stdin.js', {input: 'testing12'});63 t.is(stdout, 'testing12');64});6566test('input can be a Stream', async t => {67 const stream = new Stream.PassThrough();68 stream.write('howdy');69 stream.end();67 const {stdout} = await execa('stdin', {input: stream});70 const {stdout} = await execa('stdin.js', {input: stream});71 t.is(stdout, 'howdy');72});7374test('you can write to child.stdin', async t => {72 const subprocess = execa('stdin');75 const subprocess = execa('stdin.js');76 subprocess.stdin.end('unicorns');77 t.is((await subprocess).stdout, 'unicorns');78});7980test('input option can be a String - sync', t => {78 const {stdout} = execa.sync('stdin', {input: 'foobar'});81 const {stdout} = execaSync('stdin.js', {input: 'foobar'});82 t.is(stdout, 'foobar');83});8485test('input option can be a Buffer - sync', t => {83 const {stdout} = execa.sync('stdin', {input: Buffer.from('testing12', 'utf8')});86 const {stdout} = execaSync('stdin.js', {input: Buffer.from('testing12', 'utf8')});87 t.is(stdout, 'testing12');88});8990test('opts.stdout:ignore - stdout will not collect data', async t => {88 const {stdout} = await execa('stdin', {91 const {stdout} = await execa('stdin.js', {92 input: 'hello',90 stdio: [undefined, 'ignore', undefined]93 stdio: [undefined, 'ignore', undefined],94 });95 t.is(stdout, undefined);96});9798test('helpful error trying to provide an input stream in sync mode', t => {99 t.throws(100 () => {98 execa.sync('stdin', {input: new Stream.PassThrough()});101 execaSync('stdin.js', {input: new Stream.PassThrough()});102 },100 /The `input` option cannot be a stream in sync mode/103 {message: /The `input` option cannot be a stream in sync mode/},104 );105});106107test('maxBuffer affects stdout', async t => {105 await t.notThrowsAsync(execa('max-buffer', ['stdout', '10'], {maxBuffer: 10}));106 const {stdout, all} = await t.throwsAsync(execa('max-buffer', ['stdout', '11'], {maxBuffer: 10, all: true}), /max-buffer stdout/);108 await t.notThrowsAsync(execa('max-buffer.js', ['stdout', '10'], {maxBuffer: 10}));109 const {stdout, all} = await t.throwsAsync(execa('max-buffer.js', ['stdout', '11'], {maxBuffer: 10, all: true}), {message: /max-buffer.js stdout/});110 t.is(stdout, '.'.repeat(10));111 t.is(all, '.'.repeat(10));112});113114test('maxBuffer affects stderr', async t => {112 await t.notThrowsAsync(execa('max-buffer', ['stderr', '10'], {maxBuffer: 10}));113 const {stderr, all} = await t.throwsAsync(execa('max-buffer', ['stderr', '11'], {maxBuffer: 10, all: true}), /max-buffer stderr/);115 await t.notThrowsAsync(execa('max-buffer.js', ['stderr', '10'], {maxBuffer: 10}));116 const {stderr, all} = await t.throwsAsync(execa('max-buffer.js', ['stderr', '11'], {maxBuffer: 10, all: true}), {message: /max-buffer.js stderr/});117 t.is(stderr, '.'.repeat(10));118 t.is(all, '.'.repeat(10));119});120121test('do not buffer stdout when `buffer` set to `false`', async t => {119 const promise = execa('max-buffer', ['stdout', '10'], {buffer: false});122 const promise = execa('max-buffer.js', ['stdout', '10'], {buffer: false});123 const [result, stdout] = await Promise.all([124 promise,122 getStream(promise.stdout)125 getStream(promise.stdout),126 ]);127128 t.is(result.stdout, undefined);129 t.is(stdout, '.........\n');130});131132test('do not buffer stderr when `buffer` set to `false`', async t => {130 const promise = execa('max-buffer', ['stderr', '10'], {buffer: false});133 const promise = execa('max-buffer.js', ['stderr', '10'], {buffer: false});134 const [result, stderr] = await Promise.all([135 promise,133 getStream(promise.stderr)136 getStream(promise.stderr),137 ]);138139 t.is(result.stderr, undefined);140 t.is(stderr, '.........\n');141});142143test('do not buffer when streaming', async t => {141 const {stdout} = execa('max-buffer', ['stdout', '21'], {maxBuffer: 10});144 const {stdout} = execa('max-buffer.js', ['stdout', '21'], {maxBuffer: 10});145 const result = await getStream(stdout);146 t.is(result, '....................\n');147});148149test('buffer: false > promise resolves', async t => {147 await t.notThrowsAsync(execa('noop', {buffer: false}));150 await t.notThrowsAsync(execa('noop.js', {buffer: false}));151});152153test('buffer: false > promise resolves when output is big but is not pipable', async t => {151 await t.notThrowsAsync(execa('max-buffer', {buffer: false, stdout: 'ignore'}));154 await t.notThrowsAsync(execa('max-buffer.js', {buffer: false, stdout: 'ignore'}));155});156157test('buffer: false > promise resolves when output is big and is read', async t => {155 const subprocess = execa('max-buffer', {buffer: false});158 const subprocess = execa('max-buffer.js', {buffer: false});159 subprocess.stdout.resume();160 subprocess.stderr.resume();161 await t.notThrowsAsync(subprocess);162});163164test('buffer: false > promise resolves when output is big and "all" is used and is read', async t => {162 const subprocess = execa('max-buffer', {buffer: false, all: true});165 const subprocess = execa('max-buffer.js', {buffer: false, all: true});166 subprocess.all.resume();167 await t.notThrowsAsync(subprocess);168});169170test('buffer: false > promise rejects when process returns non-zero', async t => {168 const subprocess = execa('fail', {buffer: false});171 const subprocess = execa('fail.js', {buffer: false});172 const {exitCode} = await t.throwsAsync(subprocess);173 t.is(exitCode, 2);174});175176test('can use all: true with stdout: ignore', async t => {174 await t.notThrowsAsync(execa('max-buffer', {buffer: false, stdout: 'ignore', all: true}));177 await t.notThrowsAsync(execa('max-buffer.js', {buffer: false, stdout: 'ignore', all: true}));178});179180test('can use all: true with stderr: ignore', async t => {178 await t.notThrowsAsync(execa('max-buffer', ['stderr'], {buffer: false, stderr: 'ignore', all: true}));181 await t.notThrowsAsync(execa('max-buffer.js', ['stderr'], {buffer: false, stderr: 'ignore', all: true}));182});183184const BUFFER_TIMEOUT = 1e3;185186// On Unix (not Windows), a process won't exit if stdout has not been read.187if (process.platform !== 'win32') {188 test.serial('buffer: false > promise does not resolve when output is big and is not read', async t => {186 const {timedOut} = await t.throwsAsync(execa('max-buffer', {buffer: false, timeout: BUFFER_TIMEOUT}));189 const {timedOut} = await t.throwsAsync(execa('max-buffer.js', {buffer: false, timeout: BUFFER_TIMEOUT}));190 t.true(timedOut);191 });192193 test.serial('buffer: false > promise does not resolve when output is big and "all" is used but not read', async t => {191 const subprocess = execa('max-buffer', {buffer: false, all: true, timeout: BUFFER_TIMEOUT});194 const subprocess = execa('max-buffer.js', {buffer: false, all: true, timeout: BUFFER_TIMEOUT});195 subprocess.stdout.resume();196 subprocess.stderr.resume();197 const {timedOut} = await t.throwsAsync(subprocess);198 t.true(timedOut);
2 unmodified lines
modified:test/test.js+40 added-38 removed
1import path from 'path';1import path from 'node:path';2import process from 'node:process';3import {fileURLToPath} from 'node:url';4import test from 'ava';5import isRunning from 'is-running';6import getNode from 'get-node';5import execa from '..';7import {execa, execaSync} from '../index.js';87process.env.PATH = path.join(__dirname, 'fixtures') + path.delimiter + process.env.PATH;9process.env.PATH = fileURLToPath(new URL('./fixtures', import.meta.url)) + path.delimiter + process.env.PATH;10process.env.FOO = 'foo';1112const ENOENT_REGEXP = process.platform === 'win32' ? /failed with exit code 1/ : /spawn.* ENOENT/;1314test('execa()', async t => {13 const {stdout} = await execa('noop', ['foo']);15 const {stdout} = await execa('noop.js', ['foo']);16 t.is(stdout, 'foo');17});1819if (process.platform === 'win32') {
7 unmodified lines
27 t.is(stdout, 'Hello World');28 });29}3029test('execa.sync()', t => {30 const {stdout} = execa.sync('noop', ['foo']);31test('execaSync()', t => {32 const {stdout} = execaSync('noop.js', ['foo']);33 t.is(stdout, 'foo');34});3534test('execa.sync() throws error if written to stderr', t => {36test('execaSync() throws error if written to stderr', t => {37 t.throws(() => {36 execa.sync('foo');37 }, ENOENT_REGEXP);38 execaSync('foo');39 }, {message: ENOENT_REGEXP});40});4142test('skip throwing when using reject option', async t => {41 const {exitCode} = await execa('fail', {reject: false});43 const {exitCode} = await execa('fail.js', {reject: false});44 t.is(exitCode, 2);45});4647test('skip throwing when using reject option in sync mode', t => {46 const {exitCode} = execa.sync('fail', {reject: false});48 const {exitCode} = execaSync('fail.js', {reject: false});49 t.is(exitCode, 2);50});5152test('stripFinalNewline: true', async t => {51 const {stdout} = await execa('noop', ['foo']);53 const {stdout} = await execa('noop.js', ['foo']);54 t.is(stdout, 'foo');55});5657test('stripFinalNewline: false', async t => {56 const {stdout} = await execa('noop', ['foo'], {stripFinalNewline: false});58 const {stdout} = await execa('noop.js', ['foo'], {stripFinalNewline: false});59 t.is(stdout, 'foo\n');60});6162test('stripFinalNewline on failure', async t => {61 const {stderr} = await t.throwsAsync(execa('noop-throw', ['foo'], {stripFinalNewline: true}));63 const {stderr} = await t.throwsAsync(execa('noop-throw.js', ['foo'], {stripFinalNewline: true}));64 t.is(stderr, 'foo');65});6667test('stripFinalNewline in sync mode', t => {66 const {stdout} = execa.sync('noop', ['foo'], {stripFinalNewline: true});68 const {stdout} = execaSync('noop.js', ['foo'], {stripFinalNewline: true});69 t.is(stdout, 'foo');70});7172test('stripFinalNewline in sync mode on failure', t => {73 const {stderr} = t.throws(() => {72 execa.sync('noop-throw', ['foo'], {stripFinalNewline: true});74 execaSync('noop-throw.js', ['foo'], {stripFinalNewline: true});75 });76 t.is(stderr, 'foo');77});78
1 unmodified line
80 await t.notThrowsAsync(execa('ava', ['--version'], {preferLocal: true, env: {Path: '', PATH: ''}}));81});8283test('preferLocal: false', async t => {82 await t.throwsAsync(execa('ava', ['--version'], {preferLocal: false, env: {Path: '', PATH: ''}}), ENOENT_REGEXP);84 await t.throwsAsync(execa('ava', ['--version'], {preferLocal: false, env: {Path: '', PATH: ''}}), {message: ENOENT_REGEXP});85});8687test('preferLocal: undefined', async t => {86 await t.throwsAsync(execa('ava', ['--version'], {env: {Path: '', PATH: ''}}), ENOENT_REGEXP);88 await t.throwsAsync(execa('ava', ['--version'], {env: {Path: '', PATH: ''}}), {message: ENOENT_REGEXP});89});9091test('localDir option', async t => {92 const command = process.platform === 'win32' ? 'echo %PATH%' : 'echo $PATH';
8 unmodified lines
101 t.true(stdout.includes('6.0.0'));102});103104test('stdin errors are handled', async t => {103 const subprocess = execa('noop');105 const subprocess = execa('noop.js');106 subprocess.stdin.emit('error', new Error('test'));105 await t.throwsAsync(subprocess, /test/);107 await t.throwsAsync(subprocess, {message: /test/});108});109110test('child process errors are handled', async t => {109 const subprocess = execa('noop');111 const subprocess = execa('noop.js');112 subprocess.emit('error', new Error('test'));111 await t.throwsAsync(subprocess, /test/);113 await t.throwsAsync(subprocess, {message: /test/});114});115116test('child process errors rejects promise right away', async t => {115 const subprocess = execa('noop');117 const subprocess = execa('noop.js');118 subprocess.emit('error', new Error('test'));117 await t.throwsAsync(subprocess, /test/);119 await t.throwsAsync(subprocess, {message: /test/});120});121122test('execa() returns a promise with pid', t => {121 const {pid} = execa('noop', ['foo']);123 const {pid} = execa('noop.js', ['foo']);124 t.is(typeof pid, 'number');125});126127test('child_process.spawn() propagated errors have correct shape', t => {126 const subprocess = execa('noop', {uid: -1});128 const subprocess = execa('noop.js', {uid: -1});129 t.notThrows(() => {130 subprocess.catch(() => {});131 subprocess.unref();132 subprocess.on('error', () => {});133 });134});135136test('child_process.spawn() errors are propagated', async t => {135 const {failed} = await t.throwsAsync(execa('noop', {uid: -1}));137 const {failed} = await t.throwsAsync(execa('noop.js', {uid: -1}));138 t.true(failed);139});140141test('child_process.spawnSync() errors are propagated with a correct shape', t => {142 const {failed} = t.throws(() => {141 execa.sync('noop', {timeout: -1});143 execaSync('noop.js', {timeout: -1});144 });145 t.true(failed);146});147148test('do not try to consume streams twice', async t => {147 const subprocess = execa('noop', ['foo']);149 const subprocess = execa('noop.js', ['foo']);150 t.is((await subprocess).stdout, 'foo');151 t.is((await subprocess).stdout, 'foo');152});153154test('use relative path with \'..\' chars', async t => {153 const pathViaParentDir = path.join('..', path.basename(path.dirname(__dirname)), 'test', 'fixtures', 'noop');155 const pathViaParentDir = path.join('..', path.basename(fileURLToPath(new URL('..', import.meta.url))), 'test', 'fixtures', 'noop.js');156 const {stdout} = await execa(pathViaParentDir, ['foo']);157 t.is(stdout, 'foo');158});159160if (process.platform !== 'win32') {161 test('execa() rejects if running non-executable', async t => {160 const subprocess = execa('non-executable');162 const subprocess = execa('non-executable.js');163 await t.throwsAsync(subprocess);164 });165166 test('execa() rejects with correct error and doesn\'t throw if running non-executable with input', async t => {167 // On Node <12.6.0, `EACCESS` is emitted on `childProcess`.168 // On Node >=12.6.0, `EPIPE` is emitted on `childProcess.stdin`.167 await t.throwsAsync(execa('non-executable', {input: 'Hey!'}), /EACCES|EPIPE/);169 await t.throwsAsync(execa('non-executable.js', {input: 'Hey!'}), {message: /EACCES|EPIPE/});170 });171}172173if (process.platform !== 'win32') {
9 unmodified lines
183 });184}185186test('use environment variables by default', async t => {185 const {stdout} = await execa('environment');187 const {stdout} = await execa('environment.js');188 t.deepEqual(stdout.split('\n'), ['foo', 'undefined']);189});190191test('extend environment variables by default', async t => {190 const {stdout} = await execa('environment', [], {env: {BAR: 'bar'}});192 const {stdout} = await execa('environment.js', [], {env: {BAR: 'bar'}});193 t.deepEqual(stdout.split('\n'), ['foo', 'bar']);194});195196test('do not extend environment with `extendEnv: false`', async t => {195 const {stdout} = await execa('environment', [], {env: {BAR: 'bar', PATH: process.env.PATH}, extendEnv: false});197 const {stdout} = await execa('environment.js', [], {env: {BAR: 'bar', PATH: process.env.PATH}, extendEnv: false});198 t.deepEqual(stdout.split('\n'), ['undefined', 'bar']);199});200201test('can use `options.shell: true`', async t => {200 const {stdout} = await execa('node test/fixtures/noop foo', {shell: true});202 const {stdout} = await execa('node test/fixtures/noop.js foo', {shell: true});203 t.is(stdout, 'foo');204});205206test('can use `options.shell: string`', async t => {207 const shell = process.platform === 'win32' ? 'cmd.exe' : '/bin/bash';206 const {stdout} = await execa('node test/fixtures/noop foo', {shell});208 const {stdout} = await execa('node test/fixtures/noop.js foo', {shell});209 t.is(stdout, 'foo');210});211212test('use extend environment with `extendEnv: true` and `shell: true`', async t => {
4 unmodified lines
217 delete process.env.TEST;218});219220test('detach child process', async t => {219 const {stdout} = await execa('detach');221 const {stdout} = await execa('detach.js');222 const pid = Number(stdout);223 t.true(Number.isInteger(pid));224 t.true(isRunning(pid));225
2 unmodified lines
modified:index.d.ts+424 added-436 removed
1/// <reference types="node"/>2import {ChildProcess} from 'child_process';3import {Stream, Readable as ReadableStream} from 'stream';1import {Buffer} from 'node:buffer';2import {ChildProcess} from 'node:child_process';3import {Stream, Readable as ReadableStream} from 'node:stream';45declare namespace execa {6 type StdioOption =7 | 'pipe'8 | 'ipc'9 | 'ignore'10 | 'inherit'11 | Stream12 | number13 | undefined;5export type StdioOption =6 | 'pipe'7 | 'ipc'8 | 'ignore'9 | 'inherit'10 | Stream11 | number12 | undefined;1315 interface CommonOptions<EncodingType> {16 /**17 Kill the spawned process when the parent process exits unless either:18 - the spawned process is [`detached`](https://nodejs.org/api/child_process.html#child_process_options_detached)19 - the parent process is terminated abruptly, for example, with `SIGKILL` as opposed to `SIGTERM` or a normal exit14export interface CommonOptions<EncodingType> {15 /**16 Kill the spawned process when the parent process exits unless either:17 - the spawned process is [`detached`](https://nodejs.org/api/child_process.html#child_process_options_detached)18 - the parent process is terminated abruptly, for example, with `SIGKILL` as opposed to `SIGTERM` or a normal exit1921 @default true22 */23 readonly cleanup?: boolean;20 @default true21 */22 readonly cleanup?: boolean;2325 /**26 Prefer locally installed binaries when looking for a binary to execute.24 /**25 Prefer locally installed binaries when looking for a binary to execute.2628 If you `$ npm install foo`, you can then `execa('foo')`.27 If you `$ npm install foo`, you can then `execa('foo')`.2830 @default false31 */32 readonly preferLocal?: boolean;29 @default false30 */31 readonly preferLocal?: boolean;3234 /**35 Preferred path to find locally installed binaries in (use with `preferLocal`).33 /**34 Preferred path to find locally installed binaries in (use with `preferLocal`).3537 @default process.cwd()38 */39 readonly localDir?: string;36 @default process.cwd()37 */38 readonly localDir?: string;3941 /**42 Path to the Node.js executable to use in child processes.40 /**41 Path to the Node.js executable to use in child processes.4244 This can be either an absolute path or a path relative to the `cwd` option.43 This can be either an absolute path or a path relative to the `cwd` option.4446 Requires `preferLocal` to be `true`.45 Requires `preferLocal` to be `true`.4648 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.47 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.4850 @default process.execPath51 */52 readonly execPath?: string;49 @default process.execPath50 */51 readonly execPath?: string;5254 /**55 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.53 /**54 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.5557 If the spawned process fails, `error.stdout`, `error.stderr`, and `error.all` will contain the buffered data.56 If the spawned process fails, `error.stdout`, `error.stderr`, and `error.all` will contain the buffered data.5759 @default true60 */61 readonly buffer?: boolean;58 @default true59 */60 readonly buffer?: boolean;6163 /**64 Same options as [`stdio`](https://nodejs.org/dist/latest-v6.x/docs/api/child_process.html#child_process_options_stdio).62 /**63 Same options as [`stdio`](https://nodejs.org/dist/latest-v6.x/docs/api/child_process.html#child_process_options_stdio).6466 @default 'pipe'67 */68 readonly stdin?: StdioOption;65 @default 'pipe'66 */67 readonly stdin?: StdioOption;6870 /**71 Same options as [`stdio`](https://nodejs.org/dist/latest-v6.x/docs/api/child_process.html#child_process_options_stdio).69 /**70 Same options as [`stdio`](https://nodejs.org/dist/latest-v6.x/docs/api/child_process.html#child_process_options_stdio).7173 @default 'pipe'74 */75 readonly stdout?: StdioOption;72 @default 'pipe'73 */74 readonly stdout?: StdioOption;7577 /**78 Same options as [`stdio`](https://nodejs.org/dist/latest-v6.x/docs/api/child_process.html#child_process_options_stdio).76 /**77 Same options as [`stdio`](https://nodejs.org/dist/latest-v6.x/docs/api/child_process.html#child_process_options_stdio).7880 @default 'pipe'81 */82 readonly stderr?: StdioOption;79 @default 'pipe'80 */81 readonly stderr?: StdioOption;8284 /**85 Setting this to `false` resolves the promise with the error instead of rejecting it.83 /**84 Setting this to `false` resolves the promise with the error instead of rejecting it.8587 @default true88 */89 readonly reject?: boolean;86 @default true87 */88 readonly reject?: boolean;8991 /**92 Add an `.all` property on the promise and the resolved value. The property contains the output of the process with `stdout` and `stderr` interleaved.90 /**91 Add an `.all` property on the promise and the resolved value. The property contains the output of the process with `stdout` and `stderr` interleaved.9294 @default false95 */96 readonly all?: boolean;93 @default false94 */95 readonly all?: boolean;9698 /**99 Strip the final [newline character](https://en.wikipedia.org/wiki/Newline) from the output.97 /**98 Strip the final [newline character](https://en.wikipedia.org/wiki/Newline) from the output.99101 @default true102 */103 readonly stripFinalNewline?: boolean;100 @default true101 */102 readonly stripFinalNewline?: boolean;103105 /**106 Set to `false` if you don't want to extend the environment variables when providing the `env` property.104 /**105 Set to `false` if you don't want to extend the environment variables when providing the `env` property.106108 @default true109 */110 readonly extendEnv?: boolean;107 @default true108 */109 readonly extendEnv?: boolean;110112 /**113 Current working directory of the child process.111 /**112 Current working directory of the child process.113115 @default process.cwd()116 */117 readonly cwd?: string;114 @default process.cwd()115 */116 readonly cwd?: string;117119 /**120 Environment key-value pairs. Extends automatically from `process.env`. Set `extendEnv` to `false` if you don't want this.118 /**119 Environment key-value pairs. Extends automatically from `process.env`. Set `extendEnv` to `false` if you don't want this.120122 @default process.env123 */124 readonly env?: NodeJS.ProcessEnv;121 @default process.env122 */123 readonly env?: NodeJS.ProcessEnv;124126 /**127 Explicitly set the value of `argv[0]` sent to the child process. This will be set to `command` or `file` if not specified.128 */129 readonly argv0?: string;125 /**126 Explicitly set the value of `argv[0]` sent to the child process. This will be set to `command` or `file` if not specified.127 */128 readonly argv0?: string;129131 /**132 Child's [stdio](https://nodejs.org/api/child_process.html#child_process_options_stdio) configuration.130 /**131 Child's [stdio](https://nodejs.org/api/child_process.html#child_process_options_stdio) configuration.132134 @default 'pipe'135 */136 readonly stdio?: 'pipe' | 'ignore' | 'inherit' | readonly StdioOption[];133 @default 'pipe'134 */135 readonly stdio?: 'pipe' | 'ignore' | 'inherit' | readonly StdioOption[];136138 /**139 Specify the kind of serialization used for sending messages between processes when using the `stdio: 'ipc'` option or `execa.node()`:140 - `json`: Uses `JSON.stringify()` and `JSON.parse()`.141 - `advanced`: Uses [`v8.serialize()`](https://nodejs.org/api/v8.html#v8_v8_serialize_value)137 /**138 Specify the kind of serialization used for sending messages between processes when using the `stdio: 'ipc'` option or `execaNode()`:139 - `json`: Uses `JSON.stringify()` and `JSON.parse()`.140 - `advanced`: Uses [`v8.serialize()`](https://nodejs.org/api/v8.html#v8_v8_serialize_value)141143 Requires Node.js `13.2.0` or later.142 Requires Node.js `13.2.0` or later.143145 [More info.](https://nodejs.org/api/child_process.html#child_process_advanced_serialization)144 [More info.](https://nodejs.org/api/child_process.html#child_process_advanced_serialization)145147 @default 'json'148 */149 readonly serialization?: 'json' | 'advanced';146 @default 'json'147 */148 readonly serialization?: 'json' | 'advanced';149151 /**152 Prepare child to run independently of its parent process. Specific behavior [depends on the platform](https://nodejs.org/api/child_process.html#child_process_options_detached).150 /**151 Prepare child to run independently of its parent process. Specific behavior [depends on the platform](https://nodejs.org/api/child_process.html#child_process_options_detached).152154 @default false155 */156 readonly detached?: boolean;153 @default false154 */155 readonly detached?: boolean;156158 /**159 Sets the user identity of the process.160 */161 readonly uid?: number;157 /**158 Sets the user identity of the process.159 */160 readonly uid?: number;161163 /**164 Sets the group identity of the process.165 */166 readonly gid?: number;162 /**163 Sets the group identity of the process.164 */165 readonly gid?: number;166168 /**169 If `true`, runs `command` 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.167 /**168 If `true`, runs `command` 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.169171 We recommend against using this option since it is:172 - not cross-platform, encouraging shell-specific syntax.173 - slower, because of the additional shell interpretation.174 - unsafe, potentially allowing command injection.170 We recommend against using this option since it is:171 - not cross-platform, encouraging shell-specific syntax.172 - slower, because of the additional shell interpretation.173 - unsafe, potentially allowing command injection.174176 @default false177 */178 readonly shell?: boolean | string;175 @default false176 */177 readonly shell?: boolean | string;178180 /**181 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.179 /**180 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.181183 @default 'utf8'184 */185 readonly encoding?: EncodingType;182 @default 'utf8'183 */184 readonly encoding?: EncodingType;185187 /**188 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.186 /**187 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.188190 @default 0191 */192 readonly timeout?: number;189 @default 0190 */191 readonly timeout?: number;192194 /**195 Largest amount of data in bytes allowed on `stdout` or `stderr`. Default: 100 MB.193 /**194 Largest amount of data in bytes allowed on `stdout` or `stderr`. Default: 100 MB.195197 @default 100_000_000198 */199 readonly maxBuffer?: number;196 @default 100_000_000197 */198 readonly maxBuffer?: number;199201 /**202 Signal value to be used when the spawned process will be killed.200 /**201 Signal value to be used when the spawned process will be killed.202204 @default 'SIGTERM'205 */206 readonly killSignal?: string | number;203 @default 'SIGTERM'204 */205 readonly killSignal?: string | number;206208 /**209 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`.207 /**208 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`.209211 @default false212 */213 readonly windowsVerbatimArguments?: boolean;210 @default false211 */212 readonly windowsVerbatimArguments?: boolean;213215 /**216 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.214 /**215 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.216218 @default true219 */220 readonly windowsHide?: boolean;221 }217 @default true218 */219 readonly windowsHide?: boolean;220}221223 interface Options<EncodingType = string> extends CommonOptions<EncodingType> {224 /**225 Write some input to the `stdin` of your binary.226 */227 readonly input?: string | Buffer | ReadableStream;228 }222export interface Options<EncodingType = string> extends CommonOptions<EncodingType> {223 /**224 Write some input to the `stdin` of your binary.225 */226 readonly input?: string | Buffer | ReadableStream;227}228230 interface SyncOptions<EncodingType = string> extends CommonOptions<EncodingType> {231 /**232 Write some input to the `stdin` of your binary.233 */234 readonly input?: string | Buffer;235 }229export interface SyncOptions<EncodingType = string> extends CommonOptions<EncodingType> {230 /**231 Write some input to the `stdin` of your binary.232 */233 readonly input?: string | Buffer;234}235237 interface NodeOptions<EncodingType = string> extends Options<EncodingType> {238 /**239 The Node.js executable to use.236export interface NodeOptions<EncodingType = string> extends Options<EncodingType> {237 /**238 The Node.js executable to use.239241 @default process.execPath242 */243 readonly nodePath?: string;240 @default process.execPath241 */242 readonly nodePath?: string;243245 /**246 List of [CLI options](https://nodejs.org/api/cli.html#cli_options) passed to the Node.js executable.244 /**245 List of [CLI options](https://nodejs.org/api/cli.html#cli_options) passed to the Node.js executable.246248 @default process.execArgv249 */250 readonly nodeOptions?: string[];251 }247 @default process.execArgv248 */249 readonly nodeOptions?: string[];250}251253 interface ExecaReturnBase<StdoutStderrType> {254 /**255 The file and arguments that were run, for logging purposes.252export interface ExecaReturnBase<StdoutStderrType> {253 /**254 The file and arguments that were run, for logging purposes.255257 This is not escaped and should not be executed directly as a process, including using `execa()` or `execa.command()`.258 */259 command: string;256 This is not escaped and should not be executed directly as a process, including using `execa()` or `execaCommand()`.257 */258 command: string;259261 /**262 Same as `command` but escaped.260 /**261 Same as `command` but escaped.262264 This is meant to be copy and pasted into a shell, for debugging purposes.265 Since the escaping is fairly basic, this should not be executed directly as a process, including using `execa()` or `execa.command()`.266 */267 escapedCommand: string;263 This is meant to be copy and pasted into a shell, for debugging purposes.264 Since the escaping is fairly basic, this should not be executed directly as a process, including using `execa()` or `execaCommand()`.265 */266 escapedCommand: string;267269 /**270 The numeric exit code of the process that was run.271 */272 exitCode: number;268 /**269 The numeric exit code of the process that was run.270 */271 exitCode: number;272274 /**275 The output of the process on stdout.276 */277 stdout: StdoutStderrType;273 /**274 The output of the process on stdout.275 */276 stdout: StdoutStderrType;277279 /**280 The output of the process on stderr.281 */282 stderr: StdoutStderrType;278 /**279 The output of the process on stderr.280 */281 stderr: StdoutStderrType;282284 /**285 Whether the process failed to run.286 */287 failed: boolean;283 /**284 Whether the process failed to run.285 */286 failed: boolean;287289 /**290 Whether the process timed out.291 */292 timedOut: boolean;288 /**289 Whether the process timed out.290 */291 timedOut: boolean;292294 /**295 Whether the process was killed.296 */297 killed: boolean;293 /**294 Whether the process was killed.295 */296 killed: boolean;297299 /**300 The name of the signal that was used to terminate the process. For example, `SIGFPE`.298 /**299 The name of the signal that was used to terminate the process. For example, `SIGFPE`.300302 If a signal terminated the process, this property is defined and included in the error message. Otherwise it is `undefined`.303 */304 signal?: string;301 If a signal terminated the process, this property is defined and included in the error message. Otherwise it is `undefined`.302 */303 signal?: string;304306 /**307 A human-friendly description of the signal that was used to terminate the process. For example, `Floating point arithmetic error`.305 /**306 A human-friendly description of the signal that was used to terminate the process. For example, `Floating point arithmetic error`.307309 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.310 */311 signalDescription?: string;312 }308 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.309 */310 signalDescription?: string;311}312314 interface ExecaSyncReturnValue<StdoutErrorType = string>315 extends ExecaReturnBase<StdoutErrorType> {316 }313export interface ExecaSyncReturnValue<StdoutErrorType = string>314 extends ExecaReturnBase<StdoutErrorType> {315}316317/**318Result of a child process execution. On success this is a plain object. On failure this is also an `Error` instance.319320The child process fails when:321- its exit code is not `0`322- it was killed with a signal323- timing out324- being canceled325- there's not enough memory or there are already too many child processes326*/327export interface ExecaReturnValue<StdoutErrorType = string>328 extends ExecaSyncReturnValue<StdoutErrorType> {329 /**319 Result of a child process execution. On success this is a plain object. On failure this is also an `Error` instance.330 The output of the process with `stdout` and `stderr` interleaved.331321 The child process fails when:322 - its exit code is not `0`323 - it was killed with a signal324 - timing out325 - being canceled326 - there's not enough memory or there are already too many child processes332 This is `undefined` if either:333 - the `all` option is `false` (default value)334 - `execaSync()` was used335 */328 interface ExecaReturnValue<StdoutErrorType = string>329 extends ExecaSyncReturnValue<StdoutErrorType> {330 /**331 The output of the process with `stdout` and `stderr` interleaved.336 all?: StdoutErrorType;337333 This is `undefined` if either:334 - the `all` option is `false` (default value)335 - `execa.sync()` was used336 */337 all?: StdoutErrorType;338 /**339 Whether the process was canceled.340 */341 isCanceled: boolean;342}343339 /**340 Whether the process was canceled.341 */342 isCanceled: boolean;343 }344export interface ExecaSyncError<StdoutErrorType = string>345 extends Error,346 ExecaReturnBase<StdoutErrorType> {347 /**348 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.349345 interface ExecaSyncError<StdoutErrorType = string>346 extends Error,347 ExecaReturnBase<StdoutErrorType> {348 /**349 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.350 The child process stderr then stdout are appended to the end, separated with newlines and not interleaved.351 */352 message: string;353354 /**351 The child process stderr then stdout are appended to the end, separated with newlines and not interleaved.352 */353 message: string;355 This is the same as the `message` property except it does not include the child process stdout/stderr.356 */357 shortMessage: string;358355 /**356 This is the same as the `message` property except it does not include the child process stdout/stderr.357 */358 shortMessage: string;359 /**360 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.361360 /**361 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.362 This is `undefined` unless the child process exited due to an `error` event or a timeout.363 */364 originalMessage?: string;365}366363 This is `undefined` unless the child process exited due to an `error` event or a timeout.364 */365 originalMessage?: string;366 }367export interface ExecaError<StdoutErrorType = string>368 extends ExecaSyncError<StdoutErrorType> {369 /**370 The output of the process with `stdout` and `stderr` interleaved.371368 interface ExecaError<StdoutErrorType = string>369 extends ExecaSyncError<StdoutErrorType> {370 /**371 The output of the process with `stdout` and `stderr` interleaved.372 This is `undefined` if either:373 - the `all` option is `false` (default value)374 - `execaSync()` was used375 */376 all?: StdoutErrorType;377373 This is `undefined` if either:374 - the `all` option is `false` (default value)375 - `execa.sync()` was used376 */377 all?: StdoutErrorType;378 /**379 Whether the process was canceled.380 */381 isCanceled: boolean;382}383379 /**380 Whether the process was canceled.381 */382 isCanceled: boolean;383 }384export interface KillOptions {385 /**386 Milliseconds to wait for the child process to terminate before sending `SIGKILL`.387385 interface KillOptions {386 /**387 Milliseconds to wait for the child process to terminate before sending `SIGKILL`.388 Can be disabled with `false`.389389 Can be disabled with `false`.390 @default 5000391 */392 forceKillAfterTimeout?: number | false;393}394391 @default 5000392 */393 forceKillAfterTimeout?: number | false;394 }395export interface ExecaChildPromise<StdoutErrorType> {396 /**397 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).398396 interface ExecaChildPromise<StdoutErrorType> {397 /**398 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 This is `undefined` if either:400 - the `all` option is `false` (the default value)401 - 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)402 */403 all?: ReadableStream;404400 This is `undefined` if either:401 - the `all` option is `false` (the default value)402 - 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)403 */404 all?: ReadableStream;405 catch<ResultType = never>(406 onRejected?: (reason: ExecaError<StdoutErrorType>) => ResultType | PromiseLike<ResultType>407 ): Promise<ExecaReturnValue<StdoutErrorType> | ResultType>;408406 catch<ResultType = never>(407 onRejected?: (reason: ExecaError<StdoutErrorType>) => ResultType | PromiseLike<ResultType>408 ): Promise<ExecaReturnValue<StdoutErrorType> | ResultType>;409 /**410 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`.411 */412 kill(signal?: string, options?: KillOptions): void;413410 /**411 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`.412 */413 kill(signal?: string, options?: KillOptions): void;414415 /**416 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`.417 */418 cancel(): void;419 }420421 type ExecaChildProcess<StdoutErrorType = string> = ChildProcess &422 ExecaChildPromise<StdoutErrorType> &423 Promise<ExecaReturnValue<StdoutErrorType>>;414 /**415 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`.416 */417 cancel(): void;418}419426declare const execa: {427 /**428 Execute a file.420export type ExecaChildProcess<StdoutErrorType = string> = ChildProcess &421ExecaChildPromise<StdoutErrorType> &422Promise<ExecaReturnValue<StdoutErrorType>>;423430 Think of this as a mix of `child_process.execFile` and `child_process.spawn`.424/**425Execute a file.426432 @param file - The program/script to execute.433 @param arguments - Arguments to pass to `file` on execution.434 @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.427Think of this as a mix of `child_process.execFile` and `child_process.spawn`.428436 @example437 ```438 import execa = require('execa');429@param file - The program/script to execute.430@param arguments - Arguments to pass to `file` on execution.431@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.432440 (async () => {441 const {stdout} = await execa('echo', ['unicorns']);442 console.log(stdout);443 //=> 'unicorns'433@example434```435import {execa} from 'execa';436445 // Cancelling a spawned process437const {stdout} = await execa('echo', ['unicorns']);438console.log(stdout);439//=> 'unicorns'440447 const subprocess = execa('node');441// Cancelling a spawned process442449 setTimeout(() => {450 subprocess.cancel()451 }, 1000);443const subprocess = execa('node');444453 try {454 await subprocess;455 } catch (error) {456 console.log(subprocess.killed); // true457 console.log(error.isCanceled); // true458 }459 })();445setTimeout(() => {446 subprocess.cancel()447}, 1000);448461 // Pipe the child process stdout to the current stdout462 execa('echo', ['unicorns']).stdout.pipe(process.stdout);463 ```464 */465 (466 file: string,467 arguments?: readonly string[],468 options?: execa.Options469 ): execa.ExecaChildProcess;470 (471 file: string,472 arguments?: readonly string[],473 options?: execa.Options<null>474 ): execa.ExecaChildProcess<Buffer>;475 (file: string, options?: execa.Options): execa.ExecaChildProcess;476 (file: string, options?: execa.Options<null>): execa.ExecaChildProcess<477 Buffer478 >;449try {450 await subprocess;451} catch (error) {452 console.log(subprocess.killed); // true453 console.log(error.isCanceled); // true454}455480 /**481 Execute a file synchronously.456// Pipe the child process stdout to the current stdout457execa('echo', ['unicorns']).stdout.pipe(process.stdout);458```459*/460export function execa(461 file: string,462 arguments?: readonly string[],463 options?: Options464): ExecaChildProcess;465export function execa(466 file: string,467 arguments?: readonly string[],468 options?: Options<null>469): ExecaChildProcess<Buffer>;470export function execa(file: string, options?: Options): ExecaChildProcess;471export function execa(file: string, options?: Options<null>): ExecaChildProcess<Buffer>;472483 This method throws an `Error` if the command fails.473/**474Execute a file synchronously.475485 @param file - The program/script to execute.486 @param arguments - Arguments to pass to `file` on execution.487 @returns A result `Object` with `stdout` and `stderr` properties.488 */489 sync(490 file: string,491 arguments?: readonly string[],492 options?: execa.SyncOptions493 ): execa.ExecaSyncReturnValue;494 sync(495 file: string,496 arguments?: readonly string[],497 options?: execa.SyncOptions<null>498 ): execa.ExecaSyncReturnValue<Buffer>;499 sync(file: string, options?: execa.SyncOptions): execa.ExecaSyncReturnValue;500 sync(501 file: string,502 options?: execa.SyncOptions<null>503 ): execa.ExecaSyncReturnValue<Buffer>;476This method throws an `Error` if the command fails.477505 /**506 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')`.478@param file - The program/script to execute.479@param arguments - Arguments to pass to `file` on execution.480@returns A result `Object` with `stdout` and `stderr` properties.481*/482export function execaSync(483 file: string,484 arguments?: readonly string[],485 options?: SyncOptions486): ExecaSyncReturnValue;487export function execaSync(488 file: string,489 arguments?: readonly string[],490 options?: SyncOptions<null>491): ExecaSyncReturnValue<Buffer>;492export function execaSync(file: string, options?: SyncOptions): ExecaSyncReturnValue;493export function execaSync(494 file: string,495 options?: SyncOptions<null>496): ExecaSyncReturnValue<Buffer>;497508 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.498/**499Same as `execa()` except both file and arguments are specified in a single `command` string. For example, `execa('echo', ['unicorns'])` is the same as `execaCommand('echo unicorns')`.500510 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`.501If 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.502512 @param command - The program/script to execute and its arguments.513 @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.503The `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`.504515 @example516 ```517 import execa = require('execa');505@param command - The program/script to execute and its arguments.506@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.507519 (async () => {520 const {stdout} = await execa.command('echo unicorns');521 console.log(stdout);522 //=> 'unicorns'523 })();524 ```525 */526 command(command: string, options?: execa.Options): execa.ExecaChildProcess;527 command(command: string, options?: execa.Options<null>): execa.ExecaChildProcess<Buffer>;508@example509```510import {execaCommand} from 'execa';511529 /**530 Same as `execa.command()` but synchronous.512const {stdout} = await execaCommand('echo unicorns');513console.log(stdout);514//=> 'unicorns'515```516*/517export function execaCommand(command: string, options?: Options): ExecaChildProcess;518export function execaCommand(command: string, options?: Options<null>): ExecaChildProcess<Buffer>;519532 @param command - The program/script to execute and its arguments.533 @returns A result `Object` with `stdout` and `stderr` properties.534 */535 commandSync(command: string, options?: execa.SyncOptions): execa.ExecaSyncReturnValue;536 commandSync(command: string, options?: execa.SyncOptions<null>): execa.ExecaSyncReturnValue<Buffer>;520/**521Same as `execaCommand()` but synchronous.522538 /**539 Execute a Node.js script as a child process.523@param command - The program/script to execute and its arguments.524@returns A result `Object` with `stdout` and `stderr` properties.525*/526export function execaCommandSync(command: string, options?: SyncOptions): ExecaSyncReturnValue;527export function execaCommandSync(command: string, options?: SyncOptions<null>): ExecaSyncReturnValue<Buffer>;528541 Same as `execa('node', [scriptPath, ...arguments], options)` except (like [`child_process#fork()`](https://nodejs.org/api/child_process.html#child_process_child_process_fork_modulepath_args_options)):542 - the current Node version and options are used. This can be overridden using the `nodePath` and `nodeArguments` options.543 - the `shell` option cannot be used544 - an extra channel [`ipc`](https://nodejs.org/api/child_process.html#child_process_options_stdio) is passed to [`stdio`](#stdio)529/**530Execute a Node.js script as a child process.531546 @param scriptPath - Node.js script to execute.547 @param arguments - Arguments to pass to `scriptPath` on execution.548 @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.549 */550 node(551 scriptPath: string,552 arguments?: readonly string[],553 options?: execa.NodeOptions554 ): execa.ExecaChildProcess;555 node(556 scriptPath: string,557 arguments?: readonly string[],558 options?: execa.Options<null>559 ): execa.ExecaChildProcess<Buffer>;560 node(scriptPath: string, options?: execa.Options): execa.ExecaChildProcess;561 node(scriptPath: string, options?: execa.Options<null>): execa.ExecaChildProcess<Buffer>;562};532Same as `execa('node', [scriptPath, ...arguments], options)` except (like [`child_process#fork()`](https://nodejs.org/api/child_process.html#child_process_child_process_fork_modulepath_args_options)):533 - the current Node version and options are used. This can be overridden using the `nodePath` and `nodeArguments` options.534 - the `shell` option cannot be used535 - an extra channel [`ipc`](https://nodejs.org/api/child_process.html#child_process_options_stdio) is passed to [`stdio`](#stdio)536564export = execa;537@param scriptPath - Node.js script to execute.538@param arguments - Arguments to pass to `scriptPath` on execution.539@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.540*/541export function execaNode(542 scriptPath: string,543 arguments?: readonly string[],544 options?: NodeOptions545): ExecaChildProcess;546export function execaNode(547 scriptPath: string,548 arguments?: readonly string[],549 options?: Options<null>550): ExecaChildProcess<Buffer>;551export function execaNode(scriptPath: string, options?: Options): ExecaChildProcess;552export function execaNode(scriptPath: string, options?: Options<null>): ExecaChildProcess<Buffer>;
modified:index.js+34 added-35 removed
1'use strict';2const path = require('path');3const childProcess = require('child_process');4const crossSpawn = require('cross-spawn');5const stripFinalNewline = require('strip-final-newline');6const npmRunPath = require('npm-run-path');7const onetime = require('onetime');8const makeError = require('./lib/error');9const normalizeStdio = require('./lib/stdio');10const {spawnedKill, spawnedCancel, setupTimeout, validateTimeout, setExitHandler} = require('./lib/kill');11const {handleInput, getSpawnedResult, makeAllStream, validateInputSync} = require('./lib/stream');12const {mergePromise, getSpawnedPromise} = require('./lib/promise');13const {joinCommand, parseCommand, getEscapedCommand} = require('./lib/command');1import {Buffer} from 'node:buffer';2import path from 'node:path';3import childProcess from 'node:child_process';4import process from 'node:process';5import crossSpawn from 'cross-spawn';6import stripFinalNewline from 'strip-final-newline';7import {npmRunPathEnv} from 'npm-run-path';8import onetime from 'onetime';9import {makeError} from './lib/error.js';10import {normalizeStdio, normalizeStdioNode} from './lib/stdio.js';11import {spawnedKill, spawnedCancel, setupTimeout, validateTimeout, setExitHandler} from './lib/kill.js';12import {handleInput, getSpawnedResult, makeAllStream, validateInputSync} from './lib/stream.js';13import {mergePromise, getSpawnedPromise} from './lib/promise.js';14import {joinCommand, parseCommand, getEscapedCommand} from './lib/command.js';1516const DEFAULT_MAX_BUFFER = 1000 * 1000 * 100;1718const getEnv = ({env: envOption, extendEnv, preferLocal, localDir, execPath}) => {19 const env = extendEnv ? {...process.env, ...envOption} : envOption;2021 if (preferLocal) {21 return npmRunPath.env({env, cwd: localDir, execPath});22 return npmRunPathEnv({env, cwd: localDir, execPath});23 }2425 return env;26};
16 unmodified lines
43 reject: true,44 cleanup: true,45 all: false,46 windowsHide: true,46 ...options47 ...options,48 };4950 options.env = getEnv(options);51
8 unmodified lines
60};6162const handleOutput = (options, value, error) => {63 if (typeof value !== 'string' && !Buffer.isBuffer(value)) {63 // When `execa.sync()` errors, we normalize it to '' to mimic `execa()`64 // When `execaSync()` errors, we normalize it to '' to mimic `execa()`65 return error === undefined ? undefined : '';66 }6768 if (options.stripFinalNewline) {
2 unmodified lines
7172 return value;73};7474const execa = (file, args, options) => {75export const execa = (file, args, options) => {76 const parsed = handleArguments(file, args, options);77 const command = joinCommand(file, args);78 const escapedCommand = getEscapedCommand(file, args);79
14 unmodified lines
94 escapedCommand,95 parsed,96 timedOut: false,97 isCanceled: false,97 killed: false98 killed: false,99 }));100 return mergePromise(dummySpawned, errorPromise);101 }102
24 unmodified lines
127 escapedCommand,128 parsed,129 timedOut,130 isCanceled: context.isCanceled,130 killed: spawned.killed131 killed: spawned.killed,132 });133134 if (!parsed.options.reject) {135 return returnedError;
11 unmodified lines
147 all,148 failed: false,149 timedOut: false,150 isCanceled: false,150 killed: false151 killed: false,152 };153 };154155 const handlePromiseOnce = onetime(handlePromise);
4 unmodified lines
160161 return mergePromise(spawned, handlePromiseOnce);162};163163module.exports = execa;164165module.exports.sync = (file, args, options) => {164export const execaSync = (file, args, options) => {165 const parsed = handleArguments(file, args, options);166 const command = joinCommand(file, args);167 const escapedCommand = getEscapedCommand(file, args);168
12 unmodified lines
181 escapedCommand,182 parsed,183 timedOut: false,184 isCanceled: false,186 killed: false185 killed: false,186 });187 }188189 const stdout = handleOutput(parsed.options, result.stdout, result.error);
10 unmodified lines
200 escapedCommand,201 parsed,202 timedOut: result.error && result.error.code === 'ETIMEDOUT',203 isCanceled: false,205 killed: result.signal !== null204 killed: result.signal !== null,205 });206207 if (!parsed.options.reject) {208 return error;
10 unmodified lines
219 stderr,220 failed: false,221 timedOut: false,222 isCanceled: false,224 killed: false223 killed: false,224 };225};226228module.exports.command = (command, options) => {227export const execaCommand = (command, options) => {228 const [file, ...args] = parseCommand(command);229 return execa(file, args, options);230};231233module.exports.commandSync = (command, options) => {232export const execaCommandSync = (command, options) => {233 const [file, ...args] = parseCommand(command);235 return execa.sync(file, args, options);234 return execaSync(file, args, options);235};236238module.exports.node = (scriptPath, args, options = {}) => {237export const execaNode = (scriptPath, args, options = {}) => {238 if (args && !Array.isArray(args) && typeof args === 'object') {239 options = args;240 args = [];241 }242244 const stdio = normalizeStdio.node(options);243 const stdio = normalizeStdioNode(options);244 const defaultExecArgv = process.execArgv.filter(arg => !arg.startsWith('--inspect'));245246 const {247 nodePath = process.execPath,249 nodeOptions = defaultExecArgv248 nodeOptions = defaultExecArgv,249 } = options;250251 return execa(252 nodePath,253 [254 ...nodeOptions,255 scriptPath,257 ...(Array.isArray(args) ? args : [])256 ...(Array.isArray(args) ? args : []),257 ],258 {259 ...options,260 stdin: undefined,261 stdout: undefined,262 stderr: undefined,263 stdio,265 shell: false266 }264 shell: false,265 },266 );267};
modified:index.test-d.ts+51 added-39 removed
1import {Buffer} from 'node:buffer';2// For some reason a default import of `process` causes3// `process.stdin`, `process.stderr`, and `process.stdout`4// to get treated as `any` by `@typescript-eslint/no-unsafe-assignment`.5import * as process from 'node:process';6import {Readable as ReadableStream} from 'node:stream';7import {expectType, expectError} from 'tsd';2import {Readable as ReadableStream} from 'stream';3import execa = require('.');8import {9 execa,10 execaSync,11 execaCommand,12 execaCommandSync,13 execaNode,14 ExecaReturnValue,15 ExecaChildProcess,16 ExecaError,17 ExecaSyncReturnValue,9 ExecaSyncError10} from '.';18 ExecaSyncError,19} from './index.js';2021try {22 const execaPromise = execa('unicorns');23 execaPromise.cancel();
30 unmodified lines
54 expectType<string | undefined>(execaError.originalMessage);55}5657try {49 const unicornsResult = execa.sync('unicorns');58 const unicornsResult = execaSync('unicorns');59 expectType<string>(unicornsResult.command);60 expectType<string>(unicornsResult.escapedCommand);61 expectType<number>(unicornsResult.exitCode);62 expectType<string>(unicornsResult.stdout);
22 unmodified lines
85 expectType<string>(execaError.shortMessage);86 expectType<string | undefined>(execaError.originalMessage);87}8889/* eslint-disable @typescript-eslint/no-floating-promises */90execa('unicorns', {cleanup: false});91execa('unicorns', {preferLocal: false});92execa('unicorns', {localDir: '.'});93execa('unicorns', {execPath: '/path'});
26 unmodified lines
120execa('unicorns', {reject: false});121execa('unicorns', {stripFinalNewline: false});122execa('unicorns', {extendEnv: false});123execa('unicorns', {cwd: '.'});124// eslint-disable-next-line @typescript-eslint/naming-convention125execa('unicorns', {env: {PATH: ''}});126execa('unicorns', {argv0: ''});127execa('unicorns', {stdio: 'pipe'});128execa('unicorns', {stdio: 'ignore'});129execa('unicorns', {stdio: 'inherit'});130execa('unicorns', {120 stdio: ['pipe', 'ipc', 'ignore', 'inherit', process.stdin, 1, undefined]131 stdio: ['pipe', 'ipc', 'ignore', 'inherit', process.stdin, 1, undefined],132});133execa('unicorns', {serialization: 'advanced'});134execa('unicorns', {detached: true});135execa('unicorns', {uid: 0});
5 unmodified lines
141execa('unicorns', {killSignal: 'SIGTERM'});142execa('unicorns', {killSignal: 9});143execa('unicorns', {windowsVerbatimArguments: true});144execa('unicorns', {windowsHide: false});145/* eslint-enable @typescript-eslint/no-floating-promises */146execa('unicorns').kill();147execa('unicorns').kill('SIGKILL');148execa('unicorns').kill(undefined);149execa('unicorns').kill('SIGKILL', {});150execa('unicorns').kill('SIGKILL', {forceKillAfterTimeout: false});151execa('unicorns').kill('SIGKILL', {forceKillAfterTimeout: 42});152execa('unicorns').kill('SIGKILL', {forceKillAfterTimeout: undefined});153142expectType<ExecaChildProcess<string>>(execa('unicorns'));143expectType<ExecaReturnValue<string>>(await execa('unicorns'));144expectType<ExecaReturnValue<string>>(145 await execa('unicorns', {encoding: 'utf8'})154expectType<ExecaChildProcess>(execa('unicorns'));155expectType<ExecaReturnValue>(await execa('unicorns'));156expectType<ExecaReturnValue>(157 await execa('unicorns', {encoding: 'utf8'}),158);159expectType<ExecaReturnValue<Buffer>>(await execa('unicorns', {encoding: null}));148expectType<ExecaReturnValue<string>>(149 await execa('unicorns', ['foo'], {encoding: 'utf8'})160expectType<ExecaReturnValue>(161 await execa('unicorns', ['foo'], {encoding: 'utf8'}),162);163expectType<ExecaReturnValue<Buffer>>(152 await execa('unicorns', ['foo'], {encoding: null})164 await execa('unicorns', ['foo'], {encoding: null}),165);166155expectType<ExecaSyncReturnValue<string>>(execa.sync('unicorns'));156expectType<ExecaSyncReturnValue<string>>(157 execa.sync('unicorns', {encoding: 'utf8'})167expectType<ExecaSyncReturnValue>(execaSync('unicorns'));168expectType<ExecaSyncReturnValue>(169 execaSync('unicorns', {encoding: 'utf8'}),170);171expectType<ExecaSyncReturnValue<Buffer>>(160 execa.sync('unicorns', {encoding: null})172 execaSync('unicorns', {encoding: null}),173);162expectType<ExecaSyncReturnValue<string>>(163 execa.sync('unicorns', ['foo'], {encoding: 'utf8'})174expectType<ExecaSyncReturnValue>(175 execaSync('unicorns', ['foo'], {encoding: 'utf8'}),176);177expectType<ExecaSyncReturnValue<Buffer>>(166 execa.sync('unicorns', ['foo'], {encoding: null})178 execaSync('unicorns', ['foo'], {encoding: null}),179);180169expectType<ExecaChildProcess<string>>(execa.command('unicorns'));170expectType<ExecaReturnValue<string>>(await execa.command('unicorns'));171expectType<ExecaReturnValue<string>>(await execa.command('unicorns', {encoding: 'utf8'}));172expectType<ExecaReturnValue<Buffer>>(await execa.command('unicorns', {encoding: null}));173expectType<ExecaReturnValue<string>>(await execa.command('unicorns foo', {encoding: 'utf8'}));174expectType<ExecaReturnValue<Buffer>>(await execa.command('unicorns foo', {encoding: null}));181expectType<ExecaChildProcess>(execaCommand('unicorns'));182expectType<ExecaReturnValue>(await execaCommand('unicorns'));183expectType<ExecaReturnValue>(await execaCommand('unicorns', {encoding: 'utf8'}));184expectType<ExecaReturnValue<Buffer>>(await execaCommand('unicorns', {encoding: null}));185expectType<ExecaReturnValue>(await execaCommand('unicorns foo', {encoding: 'utf8'}));186expectType<ExecaReturnValue<Buffer>>(await execaCommand('unicorns foo', {encoding: null}));187176expectType<ExecaSyncReturnValue<string>>(execa.commandSync('unicorns'));177expectType<ExecaSyncReturnValue<string>>(execa.commandSync('unicorns', {encoding: 'utf8'}));178expectType<ExecaSyncReturnValue<Buffer>>(execa.commandSync('unicorns', {encoding: null}));179expectType<ExecaSyncReturnValue<string>>(execa.commandSync('unicorns foo', {encoding: 'utf8'}));180expectType<ExecaSyncReturnValue<Buffer>>(execa.commandSync('unicorns foo', {encoding: null}));188expectType<ExecaSyncReturnValue>(execaCommandSync('unicorns'));189expectType<ExecaSyncReturnValue>(execaCommandSync('unicorns', {encoding: 'utf8'}));190expectType<ExecaSyncReturnValue<Buffer>>(execaCommandSync('unicorns', {encoding: null}));191expectType<ExecaSyncReturnValue>(execaCommandSync('unicorns foo', {encoding: 'utf8'}));192expectType<ExecaSyncReturnValue<Buffer>>(execaCommandSync('unicorns foo', {encoding: null}));193182expectType<ExecaChildProcess<string>>(execa.node('unicorns'));183expectType<ExecaReturnValue<string>>(await execa.node('unicorns'));184expectType<ExecaReturnValue<string>>(185 await execa.node('unicorns', {encoding: 'utf8'})194expectType<ExecaChildProcess>(execaNode('unicorns'));195expectType<ExecaReturnValue>(await execaNode('unicorns'));196expectType<ExecaReturnValue>(197 await execaNode('unicorns', {encoding: 'utf8'}),198);187expectType<ExecaReturnValue<Buffer>>(await execa.node('unicorns', {encoding: null}));188expectType<ExecaReturnValue<string>>(189 await execa.node('unicorns', ['foo'], {encoding: 'utf8'})199expectType<ExecaReturnValue<Buffer>>(await execaNode('unicorns', {encoding: null}));200expectType<ExecaReturnValue>(201 await execaNode('unicorns', ['foo'], {encoding: 'utf8'}),202);203expectType<ExecaReturnValue<Buffer>>(192 await execa.node('unicorns', ['foo'], {encoding: null})204 await execaNode('unicorns', ['foo'], {encoding: null}),205);
modified:package.json+14 added-12 removed
9 unmodified lines
10 "email": "sindresorhus@gmail.com",11 "url": "https://sindresorhus.com"12 },13 "engines": {14 "node": ">=10"14 "node": "^12.20.0 || ^14.13.1 || >=16.0.0"15 },16 "type": "module",17 "exports": "./index.js",18 "scripts": {17 "test": "xo && nyc ava && tsd"19 "test": "xo && c8 ava && tsd"20 },21 "files": [22 "index.js",23 "index.d.ts",
18 unmodified lines
42 ],43 "dependencies": {44 "cross-spawn": "^7.0.3",45 "get-stream": "^6.0.0",44 "human-signals": "^2.1.0",45 "is-stream": "^2.0.0",46 "human-signals": "^3.0.1",47 "is-stream": "^3.0.0",48 "merge-stream": "^2.0.0",47 "npm-run-path": "^4.0.1",48 "onetime": "^5.1.2",49 "npm-run-path": "^5.0.1",50 "onetime": "^6.0.0",51 "signal-exit": "^3.0.3",50 "strip-final-newline": "^2.0.0"52 "strip-final-newline": "^3.0.0"53 },54 "devDependencies": {53 "@types/node": "^14.14.10",54 "ava": "^2.4.0",55 "@types/node": "^16.11.7",56 "ava": "^3.15.0",57 "c8": "^7.10.0",58 "get-node": "^11.0.1",59 "is-running": "^2.1.0",57 "nyc": "^15.1.0",60 "p-event": "^4.2.0",61 "tempfile": "^3.0.0",62 "tsd": "^0.13.1",61 "xo": "^0.35.0"63 "xo": "^0.46.4"64 },63 "nyc": {65 "c8": {66 "reporter": [67 "text",68 "lcov"69 ],
7 unmodified lines
modified:readme.md+64 added-73 removed
27 unmodified lines
2829## Usage3031```js32const execa = require('execa');32import {execa} from 'execa';3334(async () => {35 const {stdout} = await execa('echo', ['unicorns']);36 console.log(stdout);37 //=> 'unicorns'34const {stdout} = await execa('echo', ['unicorns']);35console.log(stdout);36//=> 'unicorns'38})();37```3839### Pipe the child process stdout to the parent4041```js44const execa = require('execa');42import {execa} from 'execa';4344execa('echo', ['unicorns']).stdout.pipe(process.stdout);45```4647### Handling Errors4849```js52const execa = require('execa');50import {execa} from 'execa';5154(async () => {55 // Catching an error56 try {57 await execa('unknown', ['command']);58 } catch (error) {59 console.log(error);60 /*61 {62 message: 'Command failed with ENOENT: unknown command spawn unknown ENOENT',63 errno: -2,64 code: 'ENOENT',65 syscall: 'spawn unknown',66 path: 'unknown',67 spawnargs: ['command'],68 originalMessage: 'spawn unknown ENOENT',69 shortMessage: 'Command failed with ENOENT: unknown command spawn unknown ENOENT',70 command: 'unknown command',71 escapedCommand: 'unknown command',72 stdout: '',73 stderr: '',74 all: '',75 failed: true,76 timedOut: false,77 isCanceled: false,78 killed: false52// Catching an error53try {54 await execa('unknown', ['command']);55} catch (error) {56 console.log(error);57 /*58 {59 message: 'Command failed with ENOENT: unknown command spawn unknown ENOENT',60 errno: -2,61 code: 'ENOENT',62 syscall: 'spawn unknown',63 path: 'unknown',64 spawnargs: ['command'],65 originalMessage: 'spawn unknown ENOENT',66 shortMessage: 'Command failed with ENOENT: unknown command spawn unknown ENOENT',67 command: 'unknown command',68 escapedCommand: 'unknown command',69 stdout: '',70 stderr: '',71 all: '',72 failed: true,73 timedOut: false,74 isCanceled: false,75 killed: false79 }80 */76 }8283})();77 */78}79```8081### Cancelling a spawned process8283```js89const execa = require('execa');84import {execa} from 'execa';8591(async () => {92 const subprocess = execa('node');86const subprocess = execa('node');8794 setTimeout(() => {95 subprocess.cancel();96 }, 1000);88setTimeout(() => {89 subprocess.cancel();90}, 1000);9198 try {99 await subprocess;100 } catch (error) {101 console.log(subprocess.killed); // true102 console.log(error.isCanceled); // true103 }104})()92try {93 await subprocess;94} catch (error) {95 console.log(subprocess.killed); // true96 console.log(error.isCanceled); // true97}98```99100### Catching an error with the sync method101102```js103import {execaSync} from 'execa';104105try {111 execa.sync('unknown', ['command']);106 execaSync('unknown', ['command']);107} catch (error) {108 console.log(error);109 /*110 {
73 unmodified lines
184This is `undefined` if either:185 - the [`all` option](#all-2) is `false` (the default value)186 - 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)187193### execa.sync(file, arguments?, options?)188### execaSync(file, arguments?, options?)189190Execute a file synchronously.191192Returns or throws a [`childProcessResult`](#childProcessResult).193199### execa.command(command, options?)194### execaCommand(command, options?)195201Same 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')`.196Same 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 `execaCommand('echo unicorns')`.197198If 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.199200The [`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`.201207### execa.commandSync(command, options?)202### execaCommandSync(command, options?)203209Same as [`execa.command()`](#execacommand-command-options) but synchronous.204Same as [`execaCommand()`](#execacommand-command-options) but synchronous.205206Returns or throws a [`childProcessResult`](#childProcessResult).207213### execa.node(scriptPath, arguments?, options?)208### execaNode(scriptPath, arguments?, options?)209210Execute a Node.js script as a child process.211212Same as `execa('node', [scriptPath, ...arguments], options)` except (like [`child_process#fork()`](https://nodejs.org/api/child_process.html#child_process_child_process_fork_modulepath_args_options)):
19 unmodified lines
232Type: `string`233234The file and arguments that were run, for logging purposes.235241This is not escaped and should not be executed directly as a process, including using [`execa()`](#execafile-arguments-options) or [`execa.command()`](#execacommandcommand-options).236This is not escaped and should not be executed directly as a process, including using [`execa()`](#execafile-arguments-options) or [`execaCommand()`](#execacommandcommand-options).237238#### escapedCommand239240Type: `string`241242Same as [`command`](#command) but escaped.243244This is meant to be copy and pasted into a shell, for debugging purposes.250Since 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).245Since the escaping is fairly basic, this should not be executed directly as a process, including using [`execa()`](#execafile-arguments-options) or [`execaCommand()`](#execacommandcommand-options).246247#### exitCode248249Type: `number`
19 unmodified lines
269The output of the process with `stdout` and `stderr` interleaved.270271This is `undefined` if either:272 - the [`all` option](#all-2) is `false` (the default value)278 - `execa.sync()` was used273 - `execaSync()` was used274275#### failed276277Type: `boolean`
197 unmodified lines
475476Type: `string`\477Default: `'json'`478484Specify the kind of serialization used for sending messages between processes when using the [`stdio: 'ipc'`](#stdio) option or [`execa.node()`](#execanodescriptpath-arguments-options):479Specify the kind of serialization used for sending messages between processes when using the [`stdio: 'ipc'`](#stdio) option or [`execaNode()`](#execanodescriptpath-arguments-options):480 - `json`: Uses `JSON.stringify()` and `JSON.parse()`.481 - `advanced`: Uses [`v8.serialize()`](https://nodejs.org/api/v8.html#v8_v8_serialize_value)482483Requires Node.js `13.2.0` or later.
92 unmodified lines
576577Gracefully handle failures by using automatic retries and exponential backoff with the [`p-retry`](https://github.com/sindresorhus/p-retry) package:578579```js585const pRetry = require('p-retry');580import pRetry from 'p-retry';581582const run = async () => {583 const results = await execa('curl', ['-sSL', 'https://sindresorhus.com/unicorn']);584 return results;585};586592(async () => {593 console.log(await pRetry(run, {retries: 5}));587console.log(await pRetry(run, {retries: 5}));594})();588```589590### Save and pipe output from a child process591592Let's say you want to show the output of a child process in real-time while also saving it to a variable.593594```js602const execa = require('execa');595import {execa} from 'execa';596597const subprocess = execa('echo', ['foo']);598subprocess.stdout.pipe(process.stdout);599607(async () => {608 const {stdout} = await subprocess;609 console.log('child output:', stdout);600const {stdout} = await subprocess;601console.log('child output:', stdout);610})();602```603604### Redirect output to a file605606```js616const execa = require('execa');607import {execa} from 'execa';608609const subprocess = execa('echo', ['foo'])610subprocess.stdout.pipe(fs.createWriteStream('stdout.txt'))611```612613### Redirect input from a file614615```js625const execa = require('execa');616import {execa} from 'execa';617618const subprocess = execa('cat')619fs.createReadStream('stdin.txt').pipe(subprocess.stdin)620```621622### Execute the current package's binary623624```js634const {getBinPathSync} = require('get-bin-path');625import {getBinPathSync} from 'get-bin-path';626627const binPath = getBinPathSync();628const subprocess = execa(binPath);629```
25 unmodified lines