Skip to content

Latest commit

 

History

History
428 lines (271 loc) · 10.6 KB

readme.md

File metadata and controls

428 lines (271 loc) · 10.6 KB


Build Status Coverage Status

A better child_process

Why

Install

$ npm install execa

Usage

const execa = require('execa');

(async () => {
	const {stdout} = await execa('echo', ['unicorns']);
	console.log(stdout);
	//=> 'unicorns'
})();

Additional examples:

const execa = require('execa');

(async () => {
	// Pipe the child process stdout to the current stdout
	execa('echo', ['unicorns']).stdout.pipe(process.stdout);


	// Catching an error
	try {
		await execa('wrong command');
	} catch (error) {
		console.log(error);
		/*
		{
			message: 'Command failed with exit code 2 (ENOENT): wrong command spawn wrong ENOENT',
			errno: 'ENOENT',
			syscall: 'spawn wrong',
			path: 'wrong',
			spawnargs: ['command'],
			command: 'wrong command',
			exitCode: 2,
			exitCodeName: 'ENOENT',
			stdout: '',
			stderr: '',
			all: '',
			failed: true,
			timedOut: false,
			isCanceled: false,
			killed: false
		}
		*/
	}

	// Cancelling a spawned process
	const subprocess = execa('node');
	setTimeout(() => {
		subprocess.cancel();
	}, 1000);
	try {
		await subprocess;
	} catch (error) {
		console.log(subprocess.killed); // true
		console.log(error.isCanceled); // true
	}
})();

// Catching an error with a sync method
try {
	execa.sync('wrong command');
} catch (error) {
	console.log(error);
	/*
	{
		message: 'Command failed with exit code 2 (ENOENT): wrong command spawnSync wrong ENOENT',
		errno: 'ENOENT',
		syscall: 'spawnSync wrong',
		path: 'wrong',
		spawnargs: ['command'],
		command: 'wrong command',
		exitCode: 2,
		exitCodeName: 'ENOENT',
		stdout: '',
		stderr: '',
		failed: true,
		timedOut: false,
		isCanceled: false,
		killed: false
	}
	*/
}

API

execa(file, [arguments], [options])

execa(command, [options])

Execute a file. Think of this as a mix of child_process.execFile() and child_process.spawn().

Arguments can be specified in either:

  • arguments: execa('echo', ['unicorns']).
  • command: execa('echo unicorns').

Arguments should not be escaped nor quoted, except inside command where spaces can be escaped with a backslash.

Unless the shell option is used, no shell interpreter (Bash, cmd.exe, etc.) is used, so shell features such as variables substitution (echo $PATH) are not allowed.

Returns a child_process instance which:

  • is also a Promise resolving or rejecting with a childProcessResult.
  • exposes the following additional methods and properties.

cancel()

Similar to childProcess.kill(). This is preferred when cancelling the child process execution as the error is more descriptive and childProcessResult.isCanceled is set to true.

all

Stream combining/interleaving stdout and stderr.

execa.sync(file, [arguments], [options])

execa.sync(command, [options])

Execute a file synchronously.

Returns or throws a childProcessResult.

childProcessResult

Type: object

Result of a child process execution. On success this is a plain object. On failure this is also an Error instance.

command

Type: string

The command that was run.

exitCode

Type: number

The numeric exit code of the process that was run.

exitCodeName

Type: string

The textual exit code of the process that was run.

stdout

Type: string | Buffer

The output of the process on stdout.

stderr

Type: string | Buffer

The output of the process on stderr.

all

Type: string | Buffer

The output of the process on both stdout and stderr. undefined if execa.sync() was used.

failed

Type: boolean

Whether the process failed to run.

timedOut

Type: boolean

Whether the process timed out.

isCanceled

Type: boolean

Whether the process was canceled.

killed

Type: boolean

Whether the process was killed.

signal

Type: string | undefined

The signal that was used to terminate the process.

options

Type: object

cwd

Type: string
Default: process.cwd()

Current working directory of the child process.

env

Type: object
Default: process.env

Environment key-value pairs. Extends automatically from process.env. Set extendEnv to false if you don't want this.

extendEnv

Type: boolean
Default: true

Set to false if you don't want to extend the environment variables when providing the env property.

argv0

Type: string

Explicitly set the value of argv[0] sent to the child process. This will be set to command or file if not specified.

stdio

Type: string | string[]
Default: pipe

Child's stdio configuration.

detached

Type: boolean

Prepare child to run independently of its parent process. Specific behavior depends on the platform.

uid

Type: number

Sets the user identity of the process.

gid

Type: number

Sets the group identity of the process.

shell

Type: boolean | string
Default: false

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.

We recommend against using this option since it is:

  • not cross-platform, encouraging shell-specific syntax.
  • slower, because of the additional shell interpretation.
  • unsafe, potentially allowing command injection.

stripFinalNewline

Type: boolean
Default: true

Strip the final newline character from the output.

preferLocal

Type: boolean
Default: true

Prefer locally installed binaries when looking for a binary to execute.
If you $ npm install foo, you can then execa('foo').

localDir

Type: string
Default: process.cwd()

Preferred path to find locally installed binaries in (use with preferLocal).

input

Type: string | Buffer | stream.Readable

Write some input to the stdin of your binary.
Streams are not allowed when using the synchronous methods.

reject

Type: boolean
Default: true

Setting this to false resolves the promise with the error instead of rejecting it.

cleanup

Type: boolean
Default: true

Kill the spawned process when the parent process exits unless either: - the spawned process is detached - the parent process is terminated abruptly, for example, with SIGKILL as opposed to SIGTERM or a normal exit

encoding

Type: string | null
Default: utf8

Specify the character encoding used to decode the stdout and stderr output. If set to null, then stdout and stderr will be a Buffer instead of a string.

timeout

Type: number
Default: 0

If timeout is greater than 0, the parent will send the signal identified by the killSignal property (the default is SIGTERM) if the child runs longer than timeout milliseconds.

buffer

Type: boolean
Default: true

Buffer the output from the spawned process. When buffering is disabled you must consume the output of the stdout and stderr streams because the promise will not be resolved/rejected until they have completed.

maxBuffer

Type: number
Default: 10000000 (10MB)

Largest amount of data in bytes allowed on stdout or stderr.

killSignal

Type: string | number
Default: SIGTERM

Signal value to be used when the spawned process will be killed.

stdin

Type: string | number | Stream | undefined
Default: pipe

Same options as stdio.

stdout

Type: string | number | Stream | undefined
Default: pipe

Same options as stdio.

stderr

Type: string | number | Stream | undefined
Default: pipe

Same options as stdio.

windowsVerbatimArguments

Type: boolean
Default: false

If true, no quoting or escaping of arguments is done on Windows. Ignored on other platforms. This is set to true automatically when the shell option is true.

Tips

Save and pipe output from a child process

Let's say you want to show the output of a child process in real-time while also saving it to a variable.

const execa = require('execa');

const subprocess = execa('echo', ['foo']);

subprocess.stdout.pipe(process.stdout);

(async () => {
	const {stdout} = await subprocess;
	console.log('child output:', stdout);
})();

Maintainers