Code Monkey home page Code Monkey logo

execa's Introduction


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);


	// Run a shell command
	const {stdout} = await execa.shell('echo unicorns');
	//=> 'unicorns'

	// Catching an error
	try {
		await execa.shell('exit 3');
	} catch (error) {
		console.log(error);
		/*
		{
			message: 'Command failed with exit code 3 (ESRCH): exit 3',
			code: 3,
			exitCode: 3,
			exitCodeName: 'ESRCH',
			stdout: '',
			stderr: '',
			all: '',
			failed: true,
			command: 'exit 3',
			timedOut: 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.shellSync('exit 3');
} catch (error) {
	console.log(error);
	/*
	{
		message: 'Command failed with exit code 3 (ESRCH): exit 3',
		code: 3,
		exitCode: 3,
		exitCodeName: 'ESRCH',
		stdout: '',
		stderr: '',
		failed: true,
		command: 'exit 3',
		timedOut: false
	}
	*/
}

API

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

Execute a file.

Think of this as a mix of child_process.execFile and child_process.spawn.

Returns a child_process instance which is enhanced to be a Promise.

It exposes an additional .all stream, with stdout and stderr interleaved.

The spawned process can be canceled with the .cancel() method on the promise, which causes the promise to reject an error with a .isCanceled = true property, provided the process gets canceled. The process will not be canceled if it has already exited.

The promise result is an Object with stdout, stderr and all properties.

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

Same as execa(), but returns only stdout.

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

Same as execa(), but returns only stderr.

execa.shell(command, [options])

Execute a command through the system shell. Prefer execa() whenever possible, as it's both faster and safer.

Returns a child_process instance.

The child_process instance is enhanced to also be promise for a result object with stdout and stderr properties.

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

Execute a file synchronously.

Returns the same result object as child_process.spawnSync.

It does not have the .all property that execa() has because the underlying synchronous implementation only returns stdout and stderr at the end of the execution, so they cannot be interleaved.

This method throws an Error if the command fails.

execa.shellSync(file, [options])

Execute a command synchronously through the system shell.

Returns the same result object as child_process.spawnSync.

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.

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

Keep track of the spawned process and kill it when the parent process exits.

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 null
Default: pipe

Same options as stdio.

stdout

Type: string number Stream undefined null
Default: pipe

Same options as stdio.

stderr

Type: string number Stream undefined null
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 getStream = require('get-stream');

const stream = execa('echo', ['foo']).stdout;

stream.pipe(process.stdout);

getStream(stream).then(value => {
	console.log('child output:', value);
});

Maintainers

execa's People

Contributors

acburdine avatar addaleax avatar also avatar ammarbinfaisal avatar bendingbender avatar bradfordlemley avatar brandon93s avatar dignifiedquire avatar dtinth avatar ehmicky avatar floatdrop avatar gmartigny avatar honzajavorek avatar jamestalmage avatar kevva avatar knisterpeter avatar linusu avatar lukehorvat avatar mickdekkers avatar migg24 avatar ntwb avatar samverschueren avatar satazor avatar sindresorhus avatar sonicdoe avatar strikeentco avatar tomsotte avatar

Watchers

 avatar  avatar  avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.