• Stars
    star
    6,019
  • Rank 6,689 (Top 0.2 %)
  • Language
    JavaScript
  • License
    MIT License
  • Created about 9 years ago
  • Updated about 1 year ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Process execution for humans
execa logo

Coverage Status

Process execution for humans

Why

This package improves child_process methods with:

Install

npm install execa

Usage

Promise interface

import {execa} from 'execa';

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

Scripts interface

For more information about Execa scripts, please see this page.

Basic

import {$} from 'execa';

const branch = await $`git branch --show-current`;
await $`dep deploy --branch=${branch}`;

Multiple arguments

import {$} from 'execa';

const args = ['unicorns', '&', 'rainbows!'];
const {stdout} = await $`echo ${args}`;
console.log(stdout);
//=> 'unicorns & rainbows!'

With options

import {$} from 'execa';

await $({stdio: 'inherit'})`echo unicorns`;
//=> 'unicorns'

Shared options

import {$} from 'execa';

const $$ = $({stdio: 'inherit'});

await $$`echo unicorns`;
//=> 'unicorns'

await $$`echo rainbows`;
//=> 'rainbows'

Verbose mode

> node file.js
unicorns
rainbows

> NODE_DEBUG=execa node file.js
[16:50:03.305] echo unicorns
unicorns
[16:50:03.308] echo rainbows
rainbows

Input/output

Redirect output to a file

import {execa} from 'execa';

// Similar to `echo unicorns > stdout.txt` in Bash
await execa('echo', ['unicorns']).pipeStdout('stdout.txt');

// Similar to `echo unicorns 2> stdout.txt` in Bash
await execa('echo', ['unicorns']).pipeStderr('stderr.txt');

// Similar to `echo unicorns &> stdout.txt` in Bash
await execa('echo', ['unicorns'], {all: true}).pipeAll('all.txt');

Redirect input from a file

import {execa} from 'execa';

// Similar to `cat < stdin.txt` in Bash
const {stdout} = await execa('cat', {inputFile: 'stdin.txt'});
console.log(stdout);
//=> 'unicorns'

Save and pipe output from a child process

import {execa} from 'execa';

const {stdout} = await execa('echo', ['unicorns']).pipeStdout(process.stdout);
// Prints `unicorns`
console.log(stdout);
// Also returns 'unicorns'

Pipe multiple processes

import {execa} from 'execa';

// Similar to `echo unicorns | cat` in Bash
const {stdout} = await execa('echo', ['unicorns']).pipeStdout(execa('cat'));
console.log(stdout);
//=> 'unicorns'

Handling Errors

import {execa} from 'execa';

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

Graceful termination

Using SIGTERM, and after 2 seconds, kill it with SIGKILL.

const subprocess = execa('node');

setTimeout(() => {
	subprocess.kill('SIGTERM', {
		forceKillAfterTimeout: 2000
	});
}, 1000);

API

Methods

execa(file, arguments?, options?)

Executes a command using file ...arguments. arguments are specified as an array of strings. Returns a childProcess.

Arguments are automatically escaped. They can contain any character, including spaces.

This is the preferred method when executing single commands.

execaNode(scriptPath, arguments?, options?)

Executes a Node.js file using node scriptPath ...arguments. arguments are specified as an array of strings. Returns a childProcess.

Arguments are automatically escaped. They can contain any character, including spaces.

This is the preferred method when executing Node.js files.

Like child_process#fork():

  • the current Node version and options are used. This can be overridden using the nodePath and nodeOptions options.
  • the shell option cannot be used
  • an extra channel ipc is passed to stdio

$`command`

Executes a command. The command string includes both the file and its arguments. Returns a childProcess.

Arguments are automatically escaped. They can contain any character, but spaces must use ${} like $`echo ${'has space'}`.

This is the preferred method when executing multiple commands in a script file.

The command string can inject any ${value} with the following types: string, number, childProcess or an array of those types. For example: $`echo one ${'two'} ${3} ${['four', 'five']}`. For ${childProcess}, the process's stdout is used.

For more information, please see this section and this page.

$(options)

Returns a new instance of $ but with different default options. Consecutive calls are merged to previous ones.

This can be used to either:

  • Set options for a specific command: $(options)`command`
  • Share options for multiple commands: const $$ = $(options); $$`command`; $$`otherCommand`;

execaCommand(command, options?)

Executes a command. The command string includes both the file and its arguments. Returns a childProcess.

Arguments are automatically escaped. They can contain any character, but spaces must be escaped with a backslash like execaCommand('echo has\\ space').

This is the preferred method when executing a user-supplied command string, such as in a REPL.

execaSync(file, arguments?, options?)

Same as execa() but synchronous.

Returns or throws a childProcessResult.

$.sync`command`

Same as $`command` but synchronous.

Returns or throws a childProcessResult.

execaCommandSync(command, options?)

Same as execaCommand() but synchronous.

Returns or throws a childProcessResult.

Shell syntax

For all the methods above, no shell interpreter (Bash, cmd.exe, etc.) is used unless the shell option is set. This means shell-specific characters and expressions ($variable, &&, ||, ;, |, etc.) have no special meaning and do not need to be escaped.

childProcess

The return value of all asynchronous methods is both:

kill(signal?, options?)

Same as the original child_process#kill() except: if signal is SIGTERM (the default value) and the child process is not terminated after 5 seconds, force it by sending SIGKILL.

options.forceKillAfterTimeout

Type: number | false
Default: 5000

Milliseconds to wait for the child process to terminate before sending SIGKILL.

Can be disabled with false.

all

Type: ReadableStream | undefined

Stream combining/interleaving stdout and stderr.

This is undefined if either:

pipeStdout(target)

Pipe the child process's stdout to target, which can be:

If the target is another execa() return value, it is returned. Otherwise, the original execa() return value is returned. This allows chaining pipeStdout() then awaiting the final result.

The stdout option must be kept as pipe, its default value.

pipeStderr(target)

Like pipeStdout() but piping the child process's stderr instead.

The stderr option must be kept as pipe, its default value.

pipeAll(target)

Combines both pipeStdout() and pipeStderr().

Either the stdout option or the stderr option must be kept as pipe, their default value. Also, the all option must be set to true.

childProcessResult

Type: object

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

The child process fails when:

command

Type: string

The file and arguments that were run, for logging purposes.

This is not escaped and should not be executed directly as a process, including using execa() or execaCommand().

escapedCommand

Type: string

Same as command but escaped.

This is meant to be copy and pasted into a shell, for debugging purposes. Since the escaping is fairly basic, this should not be executed directly as a process, including using execa() or execaCommand().

exitCode

Type: number

The numeric 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 | undefined

The output of the process with stdout and stderr interleaved.

This is undefined if either:

  • the all option is false (the default value)
  • execaSync() 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.

You can cancel the spawned process using the signal option.

killed

Type: boolean

Whether the process was killed.

signal

Type: string | undefined

The name of the signal that was used to terminate the process. For example, SIGFPE.

If a signal terminated the process, this property is defined and included in the error message. Otherwise it is undefined.

signalDescription

Type: string | undefined

A human-friendly description of the signal that was used to terminate the process. For example, Floating point arithmetic error.

If a signal terminated the process, this property is defined and included in the error message. Otherwise it is undefined. It is also undefined when the signal is very uncommon which should seldomly happen.

message

Type: string

Error message when the child process failed to run. In addition to the underlying error message, it also contains some information related to why the child process errored.

The child process stderr then stdout are appended to the end, separated with newlines and not interleaved.

shortMessage

Type: string

This is the same as the message property except it does not include the child process stdout/stderr.

originalMessage

Type: string | undefined

Original error message. This is the same as the message property except it includes neither the child process stdout/stderr nor some additional information added by Execa.

This is undefined unless the child process exited due to an error event or a timeout.

options

Type: object

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

preferLocal

Type: boolean
Default: true with $, false otherwise

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

localDir

Type: string | URL
Default: process.cwd()

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

execPath

Type: string
Default: process.execPath (Current Node.js executable)

Path to the Node.js executable to use in child processes.

This can be either an absolute path or a path relative to the cwd option.

Requires preferLocal to be true.

For example, this can be used together with get-node to run a specific Node.js version in a child process.

buffer

Type: boolean
Default: true

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.

If the spawned process fails, error.stdout, error.stderr, and error.all will contain the buffered data.

input

Type: string | Buffer | stream.Readable

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

If the input is a file, use the inputFile option instead.

inputFile

Type: string

Use a file as input to the the stdin of your binary.

If the input is not a file, use the input option instead.

stdin

Type: string | number | Stream | undefined
Default: inherit with $, pipe otherwise

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.

all

Type: boolean
Default: false

Add an .all property on the promise and the resolved value. The property contains the output of the process with stdout and stderr interleaved.

reject

Type: boolean
Default: true

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

stripFinalNewline

Type: boolean
Default: true

Strip the final newline character from the output.

extendEnv

Type: boolean
Default: true

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


Execa also accepts the below options which are the same as the options for child_process#spawn()/child_process#exec()

cwd

Type: string | URL
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.

argv0

Type: string

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

stdio

Type: string | string[]
Default: pipe

Child's stdio configuration.

serialization

Type: string
Default: 'json'

Specify the kind of serialization used for sending messages between processes when using the stdio: 'ipc' option or execaNode(): - json: Uses JSON.stringify() and JSON.parse(). - advanced: Uses v8.serialize()

More info.

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 file inside of a shell. Uses /bin/sh on UNIX and cmd.exe on Windows. A different shell can be specified as a string. The shell should understand the -c switch on UNIX or /d /s /c on Windows.

We recommend against using this option since it is:

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

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.

maxBuffer

Type: number
Default: 100_000_000 (100 MB)

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.

signal

Type: AbortSignal

You can abort the spawned process using AbortController.

When AbortController.abort() is called, .isCanceled becomes false.

Requires Node.js 16 or later.

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.

windowsHide

Type: boolean
Default: true

On Windows, do not create a new console window. Please note this also prevents CTRL-C from working on Windows.

verbose

Type: boolean
Default: false

Print each command on stderr before executing it.

This can also be enabled by setting the NODE_DEBUG=execa environment variable in the current process.

nodePath (For .node() only)

Type: string
Default: process.execPath

Node.js executable used to create the child process.

nodeOptions (For .node() only)

Type: string[]
Default: process.execArgv

List of CLI options passed to the Node.js executable.

Tips

Retry on error

Gracefully handle failures by using automatic retries and exponential backoff with the p-retry package:

import pRetry from 'p-retry';

const run = async () => {
	const results = await execa('curl', ['-sSL', 'https://sindresorhus.com/unicorn']);
	return results;
};

console.log(await pRetry(run, {retries: 5}));

Cancelling a spawned process

import {execa} from 'execa';

const abortController = new AbortController();
const subprocess = execa('node', [], {signal: abortController.signal});

setTimeout(() => {
	abortController.abort();
}, 1000);

try {
	await subprocess;
} catch (error) {
	console.log(subprocess.killed); // true
	console.log(error.isCanceled); // true
}

Execute the current package's binary

import {getBinPath} from 'get-bin-path';

const binPath = await getBinPath();
await execa(binPath);

execa can be combined with get-bin-path to test the current package's binary. As opposed to hard-coding the path to the binary, this validates that the package.json bin field is correctly set up.

Related

Maintainers


Get professional support for this package with a Tidelift subscription
Tidelift helps make open source sustainable for maintainers while giving companies
assurances about security, maintenance, and licensing for their dependencies.

More Repositories

1

awesome

๐Ÿ˜Ž Awesome lists about all kinds of interesting topics
270,042
star
2

awesome-nodejs

โšก Delightful Node.js packages and resources
52,854
star
3

awesome-electron

Useful resources for creating apps with Electron
25,634
star
4

quick-look-plugins

List of useful Quick Look plugins for developers
17,497
star
5

got

๐ŸŒ Human-friendly and powerful HTTP request library for Node.js
TypeScript
14,218
star
6

type-fest

A collection of essential TypeScript types
TypeScript
14,015
star
7

ky

๐ŸŒณ Tiny & elegant JavaScript HTTP client based on the Fetch API
TypeScript
13,762
star
8

pure

Pretty, minimal and fast ZSH prompt
Shell
12,391
star
9

pageres

Capture website screenshots
TypeScript
9,573
star
10

ora

Elegant terminal spinner
JavaScript
8,591
star
11

np

A better `npm publish`
JavaScript
7,529
star
12

github-markdown-css

The minimal amount of CSS to replicate the GitHub Markdown style
CSS
7,421
star
13

caprine

Elegant Facebook Messenger desktop app
TypeScript
7,014
star
14

screenfull

Simple wrapper for cross-browser usage of the JavaScript Fullscreen API
HTML
6,891
star
15

Gifski

๐ŸŒˆ Convert videos to high-quality GIFs on your Mac
Swift
6,807
star
16

fkill-cli

Fabulously kill processes. Cross-platform.
JavaScript
6,782
star
17

query-string

Parse and stringify URL query strings
JavaScript
6,453
star
18

modern-normalize

๐Ÿ’ Normalize browsers' default style
TypeScript
5,038
star
19

css-in-readme-like-wat

Style your readme using CSS with this simple trick
5,013
star
20

awesome-npm

Awesome npm resources and tips
4,315
star
21

promise-fun

Promise packages, patterns, chat, and tutorials
4,277
star
22

awesome-scifi

Sci-Fi worth consuming
4,268
star
23

electron-store

Simple data persistence for your Electron app or module - Save and load user preferences, app state, cache, etc
JavaScript
4,165
star
24

create-dmg

Create a good-looking DMG for your macOS app in seconds
JavaScript
3,950
star
25

speed-test

Test your internet connection speed and ping using speedtest.net from the CLI
JavaScript
3,882
star
26

eslint-plugin-unicorn

More than 100 powerful ESLint rules
JavaScript
3,877
star
27

ow

Function argument validation for humans
TypeScript
3,799
star
28

file-type

Detect the file type of a file, stream, or data
JavaScript
3,632
star
29

meow

๐Ÿˆ CLI app helper
JavaScript
3,305
star
30

p-queue

Promise queue with concurrency control
TypeScript
3,202
star
31

open

Open stuff like URLs, files, executables. Cross-platform.
JavaScript
2,976
star
32

Plash

๐Ÿ’ฆ Make any website your Mac desktop wallpaper
Swift
2,735
star
33

alfy

Create Alfred workflows with ease
JavaScript
2,570
star
34

trash

Move files and directories to the trash
JavaScript
2,512
star
35

fast-cli

Test your download and upload speed using fast.com
JavaScript
2,484
star
36

guides

A collection of succinct guides - Public Domain
2,424
star
37

globby

User-friendly glob matching
JavaScript
2,376
star
38

slugify

Slugify a string
JavaScript
2,357
star
39

emoj

Find relevant emoji from text on the command-line ๐Ÿ˜ฎ โœจ ๐Ÿ™Œ ๐Ÿด ๐Ÿ’ฅ ๐Ÿ™ˆ
JavaScript
2,311
star
40

cli-spinners

Spinners for use in the terminal
JavaScript
2,255
star
41

on-change

Watch an object or array for changes
JavaScript
1,966
star
42

devtools-detect

Detect if DevTools is open and its orientation
HTML
1,924
star
43

gulp-imagemin

Minify PNG, JPEG, GIF and SVG images
JavaScript
1,903
star
44

touch-bar-simulator

Use the Touch Bar on any Mac
Swift
1,900
star
45

notifier-for-github

Browser extension - Get notified about new GitHub notifications
JavaScript
1,828
star
46

editorconfig-sublime

Sublime Text plugin for EditorConfig - Helps developers maintain consistent coding styles between different editors
Python
1,757
star
47

emittery

Simple and modern async event emitter
JavaScript
1,721
star
48

is

Type check values
TypeScript
1,678
star
49

capture-website

Capture screenshots of websites
JavaScript
1,670
star
50

Defaults

๐Ÿ’พ Swifty and modern UserDefaults
Swift
1,661
star
51

electron-boilerplate

Boilerplate to kickstart creating an app with Electron
JavaScript
1,632
star
52

pageres-cli

Capture website screenshots
JavaScript
1,620
star
53

clipboardy

Access the system clipboard (copy/paste)
JavaScript
1,598
star
54

gulp-rev

Static asset revisioning by appending content hash to filenames: `unicorn.css` โ†’ `unicorn-d41d8cd98f.css`
JavaScript
1,538
star
55

pify

Promisify a callback-style function
JavaScript
1,494
star
56

boxen

Create boxes in the terminal
JavaScript
1,467
star
57

Actions

โš™๏ธ Supercharge your shortcuts
Swift
1,437
star
58

multiline

Multiline strings in JavaScript
JavaScript
1,424
star
59

hyper-snazzy

Elegant Hyper theme with bright colors
JavaScript
1,412
star
60

amas

Awesome & Marvelous Amas
1,392
star
61

LaunchAtLogin

Add โ€œLaunch at Loginโ€ functionality to your macOS app in seconds
Swift
1,346
star
62

del

Delete files and directories
JavaScript
1,316
star
63

refined-twitter

Browser extension that simplifies the Twitter interface and adds useful features
JavaScript
1,313
star
64

KeyboardShortcuts

โŒจ๏ธ Add user-customizable global keyboard shortcuts (hotkeys) to your macOS app in minutes
Swift
1,313
star
65

iterm2-snazzy

Elegant iTerm2 theme with bright colors
1,313
star
66

electron-context-menu

Context menu for your Electron app
JavaScript
1,297
star
67

p-limit

Run multiple promise-returning & async functions with limited concurrency
JavaScript
1,294
star
68

Settings

โš™ Add a settings window to your macOS app in minutes
Swift
1,282
star
69

trash-cli

Move files and folders to the trash
JavaScript
1,244
star
70

electron-util

Useful utilities for Electron apps and modules
JavaScript
1,188
star
71

is-online

Check if the internet connection is up
JavaScript
1,181
star
72

ponyfill

๐Ÿฆ„ Like polyfill but with pony pureness
1,136
star
73

conf

Simple config handling for your app or module
TypeScript
1,109
star
74

anatine

[DEPRECATED] ๐Ÿฆ Pristine Twitter app
JavaScript
1,097
star
75

electron-dl

Simplified file downloads for your Electron app
JavaScript
1,087
star
76

log-update

Log by overwriting the previous output in the terminal. Useful for rendering progress bars, animations, etc.
JavaScript
1,027
star
77

pretty-bytes

Convert bytes to a human readable string: 1337 โ†’ 1.34 kB
JavaScript
1,022
star
78

grunt-sass

Compile Sass to CSS
JavaScript
1,020
star
79

mem

Memoize functions - an optimization technique used to speed up consecutive function calls by caching the result of calls with identical input
TypeScript
1,019
star
80

DockProgress

Show progress in your app's Dock icon
Swift
1,003
star
81

wallpaper

Manage the desktop wallpaper
JavaScript
996
star
82

p-map

Map over promises concurrently
JavaScript
996
star
83

public-ip

Get your public IP address - very fast!
JavaScript
979
star
84

gulp-app

[DEPRECATED] Gulp as an app
JavaScript
961
star
85

grunt-shell

Run shell commands
JavaScript
952
star
86

load-grunt-tasks

Load multiple grunt tasks using globbing patterns
JavaScript
940
star
87

hasha

Hashing made simple. Get the hash of a buffer/string/stream/file.
JavaScript
934
star
88

pretty-ms

Convert milliseconds to a human readable string: `1337000000` โ†’ `15d 11h 23m 20s`
JavaScript
929
star
89

terminal-image

Display images in the terminal
JavaScript
923
star
90

object-assign

ES2015 Object.assign() ponyfill
JavaScript
922
star
91

copy-text-to-clipboard

Copy text to the clipboard in modern browsers (0.2 kB)
JavaScript
858
star
92

System-Color-Picker

๐ŸŽจ The macOS color picker as an app with more features
Swift
842
star
93

normalize-url

Normalize a URL
JavaScript
818
star
94

get-port

Get an available TCP port
JavaScript
817
star
95

atom-editorconfig

Helps developers maintain consistent coding styles between different editors
JavaScript
811
star
96

grunt-concurrent

Run grunt tasks concurrently
JavaScript
799
star
97

dot-prop

Get, set, or delete a property from a nested object using a dot path
JavaScript
777
star
98

p-progress

Create a promise that reports progress
TypeScript
751
star
99

gulp-changed

Only pass through changed files
JavaScript
747
star
100

generator-nm

Scaffold out a node module
JavaScript
742
star