execa
- Version 9.6.0
- Published
- 324 kB
- 12 dependencies
- MIT license
Install
npm i execayarn add execapnpm add execaOverview
Process execution for humans
Index
Variables
Functions
Classes
Type Aliases
Variables
variable $
const $: ExecaScriptMethod<{}>;Same as
execa()but using script-friendly default options.When
commandis a template string, it includes both thefileand itsarguments.$(options)can be used to return a new instance of this method but with different defaultoptions. Consecutive calls are merged to previous ones.This is the preferred method when executing multiple commands in a script file.
Returns
A
ResultPromisethat is both: - the subprocess. - aPromiseeither resolving with its successfulresult, or rejecting with itserror.Throws
ExecaErrorExample 1
Basic
import {$} from 'execa';const branch = await $`git branch --show-current`;await $`dep deploy --branch=${branch}`;Example 2
Verbose mode
$ node build.jsBuilding application...Done building.Running tests...Error: the entrypoint is invalid.$ NODE_DEBUG=execa node build.js[00:57:44.581] [0] $ npm run build[00:57:44.653] [0] Building application...[00:57:44.653] [0] Done building.[00:57:44.658] [0] ✔ (done in 78ms)[00:57:44.658] [1] $ npm run test[00:57:44.740] [1] Running tests...[00:57:44.740] [1] Error: the entrypoint is invalid.[00:57:44.747] [1] ✘ Command failed with exit code 1: npm run test[00:57:44.747] [1] ✘ (done in 89ms)
variable execa
const execa: ExecaMethod<{}>;Executes a command using
file ...arguments.When
commandis a template string, it includes both thefileand itsarguments.execa(options)can be used to return a new instance of this method but with different defaultoptions. Consecutive calls are merged to previous ones.Parameter file
The program/script to execute, as a string or file URL
Parameter arguments
Arguments to pass to
fileon execution.Returns
A
ResultPromisethat is both: - the subprocess. - aPromiseeither resolving with its successfulresult, or rejecting with itserror.Throws
ExecaErrorExample 1
Simple syntax
import {execa} from 'execa';const {stdout} = await execa`npm run build`;// Print command's outputconsole.log(stdout);Example 2
Script
import {$} from 'execa';const {stdout: name} = await $`cat package.json`.pipe`grep name`;console.log(name);const branch = await $`git branch --show-current`;await $`dep deploy --branch=${branch}`;await Promise.all([$`sleep 1`,$`sleep 2`,$`sleep 3`,]);const directoryName = 'foo bar';await $`mkdir /tmp/${directoryName}`;Example 3
Local binaries
$ npm install -D eslintawait execa({preferLocal: true})`eslint`;Example 4
Pipe multiple subprocesses
const {stdout, pipedFrom} = await execa`npm run build`.pipe`sort`.pipe`head -n 2`;// Output of `npm run build | sort | head -n 2`console.log(stdout);// Output of `npm run build | sort`console.log(pipedFrom[0].stdout);// Output of `npm run build`console.log(pipedFrom[0].pipedFrom[0].stdout);Example 5
Interleaved output
const {all} = await execa({all: true})`npm run build`;// stdout + stderr, interleavedconsole.log(all);Example 6
Programmatic + terminal output
const {stdout} = await execa({stdout: ['pipe', 'inherit']})`npm run build`;// stdout is also printed to the terminalconsole.log(stdout);Example 7
Simple input
const getInputString = () => { /* ... *\/ };const {stdout} = await execa({input: getInputString()})`sort`;console.log(stdout);Example 8
File input
// Similar to: npm run build < input.txtawait execa({stdin: {file: 'input.txt'}})`npm run build`;Example 9
File output
// Similar to: npm run build > output.txtawait execa({stdout: {file: 'output.txt'}})`npm run build`;Example 10
Split into text lines
const {stdout} = await execa({lines: true})`npm run build`;// Print first 10 linesconsole.log(stdout.slice(0, 10).join('\n'));Example 11
Iterate over text lines
for await (const line of execa`npm run build`) {if (line.includes('WARN')) {console.warn(line);}}Example 12
Transform/filter output
let count = 0;// Filter out secret lines, then prepend the line numberconst transform = function * (line) {if (!line.includes('secret')) {yield `[${count++}] ${line}`;}};await execa({stdout: transform})`npm run build`;Example 13
Web streams
const response = await fetch('https://example.com');await execa({stdin: response.body})`sort`;Example 14
Convert to Duplex stream
import {execa} from 'execa';import {pipeline} from 'node:stream/promises';import {createReadStream, createWriteStream} from 'node:fs';await pipeline(createReadStream('./input.txt'),execa`node ./transform.js`.duplex(),createWriteStream('./output.txt'),);Example 15
Exchange messages
// parent.jsimport {execaNode} from 'execa';const subprocess = execaNode`child.js`;await subprocess.sendMessage('Hello from parent');const message = await subprocess.getOneMessage();console.log(message); // 'Hello from child'// child.jsimport {getOneMessage, sendMessage} from 'execa';const message = await getOneMessage(); // 'Hello from parent'const newMessage = message.replace('parent', 'child'); // 'Hello from child'await sendMessage(newMessage);Example 16
Any input type
// main.jsimport {execaNode} from 'execa';const ipcInput = [{task: 'lint', ignore: /test\.js/},{task: 'copy', files: new Set(['main.js', 'index.js']),}];await execaNode({ipcInput})`build.js`;// build.jsimport {getOneMessage} from 'execa';const ipcInput = await getOneMessage();Example 17
Any output type
// main.jsimport {execaNode} from 'execa';const {ipcOutput} = await execaNode`build.js`;console.log(ipcOutput[0]); // {kind: 'start', timestamp: date}console.log(ipcOutput[1]); // {kind: 'stop', timestamp: date}// build.jsimport {sendMessage} from 'execa';const runBuild = () => { /* ... *\/ };await sendMessage({kind: 'start', timestamp: new Date()});await runBuild();await sendMessage({kind: 'stop', timestamp: new Date()});Example 18
Graceful termination
// main.jsimport {execaNode} from 'execa';const controller = new AbortController();setTimeout(() => {controller.abort();}, 5000);await execaNode({cancelSignal: controller.signal,gracefulCancel: true,})`build.js`;// build.jsimport {getCancelSignal} from 'execa';const cancelSignal = await getCancelSignal();const url = 'https://example.com/build/info';const response = await fetch(url, {signal: cancelSignal});Example 19
Detailed error
import {execa, ExecaError} from 'execa';try {await execa`unknown command`;} catch (error) {if (error instanceof ExecaError) {console.log(error);}/*ExecaError: Command failed with ENOENT: unknown commandspawn unknown ENOENTat ...at ... {shortMessage: 'Command failed with ENOENT: unknown command\nspawn unknown ENOENT',originalMessage: 'spawn unknown ENOENT',command: 'unknown command',escapedCommand: 'unknown command',cwd: '/path/to/cwd',durationMs: 28.217566,failed: true,timedOut: false,isCanceled: false,isTerminated: false,isMaxBuffer: false,code: 'ENOENT',stdout: '',stderr: '',stdio: [undefined, '', ''],pipedFrom: [][cause]: Error: spawn unknown ENOENTat ...at ... {errno: -2,code: 'ENOENT',syscall: 'spawn unknown',path: 'unknown',spawnargs: [ 'command' ]}}\/}Example 20
Verbose mode
await execa`npm run build`;await execa`npm run test`;$ NODE_DEBUG=execa node build.js[00:57:44.581] [0] $ npm run build[00:57:44.653] [0] Building application...[00:57:44.653] [0] Done building.[00:57:44.658] [0] ✔ (done in 78ms)[00:57:44.658] [1] $ npm run test[00:57:44.740] [1] Running tests...[00:57:44.740] [1] Error: the entrypoint is invalid.[00:57:44.747] [1] ✘ Command failed with exit code 1: npm run test[00:57:44.747] [1] ✘ (done in 89ms)Example 21
Custom logging
import {execa as execa_} from 'execa';import {createLogger, transports} from 'winston';// Log to a file using Winstonconst transport = new transports.File({filename: 'logs.txt'});const logger = createLogger({transports: [transport]});const LOG_LEVELS = {command: 'info',output: 'verbose',ipc: 'verbose',error: 'error',duration: 'info',};const execa = execa_({verbose(verboseLine, {message, ...verboseObject}) {const level = LOG_LEVELS[verboseObject.type];logger[level](message, verboseObject);},});await execa`npm run build`;await execa`npm run test`;
variable execaCommand
const execaCommand: ExecaCommandMethod<{}>;Executes a command.
commandis a string that includes both thefileand itsarguments.When
commandis a template string, it includes both thefileand itsarguments.execaCommand(options)can be used to return a new instance of this method but with different defaultoptions. Consecutive calls are merged to previous ones.This is only intended for very specific cases, such as a REPL. This should be avoided otherwise.
Parameter command
The program/script to execute and its arguments.
Returns
A
ResultPromisethat is both: - the subprocess. - aPromiseeither resolving with its successfulresult, or rejecting with itserror.Throws
ExecaErrorExample 1
import {execaCommand} from 'execa';for await (const commandAndArguments of getReplLine()) {await execaCommand(commandAndArguments);}
variable execaCommandSync
const execaCommandSync: ExecaCommandSyncMethod<{}>;Same as
execaCommand()but synchronous.When
commandis a template string, it includes both thefileand itsarguments.execaCommandSync(options)can be used to return a new instance of this method but with different defaultoptions. Consecutive calls are merged to previous ones.Returns a subprocess
resultor throws anerror. Thesubprocessis not returned: its methods and properties are not available.Parameter command
The program/script to execute and its arguments.
Returns
SyncResultThrows
ExecaSyncErrorExample 1
import {execaCommandSync} from 'execa';for (const commandAndArguments of getReplLine()) {execaCommandSync(commandAndArguments);}
variable execaNode
const execaNode: ExecaNodeMethod<{}>;Same as
execa()but using thenode: trueoption. Executes a Node.js file usingnode scriptPath ...arguments.When
commandis a template string, it includes both thefileand itsarguments.execaNode(options)can be used to return a new instance of this method but with different defaultoptions. Consecutive calls are merged to previous ones.This is the preferred method when executing Node.js files.
Parameter scriptPath
Node.js script to execute, as a string or file URL
Parameter arguments
Arguments to pass to
scriptPathon execution.Returns
A
ResultPromisethat is both: - the subprocess. - aPromiseeither resolving with its successfulresult, or rejecting with itserror.Throws
ExecaErrorExample 1
import {execaNode, execa} from 'execa';await execaNode`file.js argument`;// Is the same as:await execa({node: true})`file.js argument`;// Or:await execa`node file.js argument`;
variable execaSync
const execaSync: ExecaSyncMethod<{}>;Same as
execa()but synchronous.Returns a subprocess
resultor throws anerror. Thesubprocessis not returned: its methods and properties are not available.When
commandis a template string, it includes both thefileand itsarguments.execaSync(options)can be used to return a new instance of this method but with different defaultoptions. Consecutive calls are merged to previous ones.This method is discouraged as it holds the CPU and lacks multiple features.
Parameter file
The program/script to execute, as a string or file URL
Parameter arguments
Arguments to pass to
fileon execution.Returns
SyncResultThrows
ExecaSyncErrorExample 1
import {execaSync} from 'execa';const {stdout} = execaSync`npm run build`;// Print command's outputconsole.log(stdout);
Functions
function getCancelSignal
getCancelSignal: () => Promise<AbortSignal>;Retrieves the [
AbortSignal](https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal) shared by thecancelSignaloption.This can only be called inside a subprocess. This requires the
gracefulCanceloption to betrue.
function getEachMessage
getEachMessage: ( getEachMessageOptions?: GetEachMessageOptions) => AsyncIterableIterator<Message>;Iterate over each
messagefrom the parent process.This requires the
ipcoption to betrue. The type ofmessagedepends on theserializationoption.
function getOneMessage
getOneMessage: ( getOneMessageOptions?: GetOneMessageOptions<Options['serialization']>) => Promise<Message>;Receive a single
messagefrom the parent process.This requires the
ipcoption to betrue. The type ofmessagedepends on theserializationoption.
function parseCommandString
parseCommandString: (command: string) => string[];Split a
commandstring into an array. For example,'npm run build'returns['npm', 'run', 'build']and'argument otherArgument'returns['argument', 'otherArgument'].Parameter command
The file to execute and/or its arguments.
Returns
fileOrArgument[]
Example 1
import {execa, parseCommandString} from 'execa';const commandString = 'npm run task';const commandArray = parseCommandString(commandString);await execa`${commandArray}`;const [file, ...commandArguments] = commandArray;await execa(file, commandArguments);
function sendMessage
sendMessage: ( message: Message, sendMessageOptions?: SendMessageOptions) => Promise<void>;Send a
messageto the parent process.This requires the
ipcoption to betrue. The type ofmessagedepends on theserializationoption.
Classes
class ExecaError
class ExecaError<OptionsType extends Options = Options> extends CommonError< false, OptionsType> {}Result of a subprocess failed execution.
This error is thrown as an exception. If the
rejectoption is false, it is returned instead.This has the same shape as successful results, with a few additional properties.
property name
readonly name: string;class ExecaSyncError
class ExecaSyncError< OptionsType extends SyncOptions = SyncOptions> extends CommonError<true, OptionsType> {}Result of a subprocess failed execution.
This error is thrown as an exception. If the
rejectoption is false, it is returned instead.This has the same shape as successful results, with a few additional properties.
property name
readonly name: string;Type Aliases
type ExecaMethod
type ExecaMethod<OptionsType extends Options = Options> = ExecaBind<OptionsType> & ExecaTemplate<OptionsType> & ExecaArrayLong<OptionsType> & ExecaArrayShort<OptionsType>;execa()method either exported by Execa, or bound usingexeca(options).
type ExecaNodeMethod
type ExecaNodeMethod<OptionsType extends Options = Options> = ExecaNodeBind<OptionsType> & ExecaNodeTemplate<OptionsType> & ExecaNodeArrayLong<OptionsType> & ExecaNodeArrayShort<OptionsType>;execaNode()method either exported by Execa, or bound usingexecaNode(options).
type ExecaScriptMethod
type ExecaScriptMethod<OptionsType extends CommonOptions = CommonOptions> = ExecaScriptBind<OptionsType> & ExecaScriptTemplate<OptionsType> & ExecaScriptArrayLong<OptionsType> & ExecaScriptArrayShort<OptionsType> & { sync: ExecaScriptSyncMethod<OptionsType>; } & { s: ExecaScriptSyncMethod<OptionsType> };$()method either exported by Execa, or bound using$(options).
type ExecaScriptSyncMethod
type ExecaScriptSyncMethod<OptionsType extends CommonOptions = CommonOptions> = ExecaScriptSyncBind<OptionsType> & ExecaScriptSyncTemplate<OptionsType> & ExecaScriptSyncArrayLong<OptionsType> & ExecaScriptSyncArrayShort<OptionsType>;$.sync()method either exported by Execa, or bound using$.sync(options).
type ExecaSyncMethod
type ExecaSyncMethod<OptionsType extends SyncOptions = SyncOptions> = ExecaSyncBind<OptionsType> & ExecaSyncTemplate<OptionsType> & ExecaSyncArrayLong<OptionsType> & ExecaSyncArrayShort<OptionsType>;type Message
type Message< Serialization extends Options['serialization'] = Options['serialization']> = Serialization extends 'json' ? JsonMessage : AdvancedMessage;Type of messages exchanged between a process and its subprocess using
sendMessage(),getOneMessage()andgetEachMessage().This requires the
ipcoption to betrue. The type ofmessagedepends on theserializationoption.
type Options
type Options = CommonOptions<false>;Subprocess options.
Some options are related to the subprocess output:
verbose,lines,stripFinalNewline,buffer,maxBuffer. By default, those options apply to all file descriptors (stdout,stderr, etc.). A plain object can be passed instead to apply them to onlystdout,stderr,all(both stdout and stderr),ipc,fd3, etc.Example 1
// Same value for stdout and stderrawait execa({verbose: 'full'})`npm run build`;// Different values for stdout and stderrawait execa({verbose: {stdout: 'none', stderr: 'full'}})`npm run build`;
type Result
type Result<OptionsType extends Options = Options> = SuccessResult< false, OptionsType>;Result of a subprocess successful execution.
When the subprocess fails, it is rejected with an
ExecaErrorinstead.
type ResultPromise
type ResultPromise<OptionsType extends Options = Options> = Subprocess<OptionsType> & Promise<Result<OptionsType>>;The return value of all asynchronous methods is both: - the subprocess. - a
Promiseeither resolving with its successfulresult, or rejecting with itserror.
type StdinOption
type StdinOption = StdinOptionCommon<false, false>;type StdinSyncOption
type StdinSyncOption = StdinOptionCommon<true, false>;type StdoutStderrOption
type StdoutStderrOption = StdoutStderrOptionCommon<false, false>;type StdoutStderrSyncOption
type StdoutStderrSyncOption = StdoutStderrOptionCommon<true, false>;type Subprocess
type Subprocess<OptionsType extends Options = Options> = Omit< ChildProcess, keyof ExecaCustomSubprocess<OptionsType>> & ExecaCustomSubprocess<OptionsType>;[
child_processinstance](https://nodejs.org/api/child_process.html#child_process_class_childprocess) with additional methods and properties.
type SyncOptions
type SyncOptions = CommonOptions<true>;Subprocess options, with synchronous methods.
Some options are related to the subprocess output:
verbose,lines,stripFinalNewline,buffer,maxBuffer. By default, those options apply to all file descriptors (stdout,stderr, etc.). A plain object can be passed instead to apply them to onlystdout,stderr,all(both stdout and stderr),ipc,fd3, etc.Example 1
// Same value for stdout and stderrexecaSync({verbose: 'full'})`npm run build`;// Different values for stdout and stderrexecaSync({verbose: {stdout: 'none', stderr: 'full'}})`npm run build`;
type SyncResult
type SyncResult<OptionsType extends SyncOptions = SyncOptions> = SuccessResult< true, OptionsType>;Result of a subprocess successful execution.
When the subprocess fails, it is rejected with an
ExecaErrorinstead.
type SyncVerboseObject
type SyncVerboseObject = GenericVerboseObject & { /** The options passed to the subprocess. */ options: SyncOptions;
/** Subprocess result.
This is `undefined` if `verboseObject.type` is `'command'`, `'output'` or `'ipc'`. */ result?: SyncResult;};Subprocess event object, for logging purpose, using the
verboseoption andexecaSync().
type TemplateExpression
type TemplateExpression = TemplateExpressionItem | readonly TemplateExpressionItem[];Value allowed inside
${...}when using the template string syntax.
type VerboseObject
type VerboseObject = GenericVerboseObject & { /** The options passed to the subprocess. */ options: Options;
/** Subprocess result.
This is `undefined` if `verboseObject.type` is `'command'`, `'output'` or `'ipc'`. */ result?: Result;};Subprocess event object, for logging purpose, using the
verboseoption andexeca().
Package Files (14)
- index.d.ts
- types/arguments/options.d.ts
- types/ipc.d.ts
- types/methods/command.d.ts
- types/methods/main-async.d.ts
- types/methods/main-sync.d.ts
- types/methods/node.d.ts
- types/methods/script.d.ts
- types/methods/template.d.ts
- types/return/final-error.d.ts
- types/return/result.d.ts
- types/stdio/type.d.ts
- types/subprocess/subprocess.d.ts
- types/verbose.d.ts
Dependencies (12)
Dev Dependencies (14)
Peer Dependencies (0)
No peer dependencies.
Badge
To add a badge like this oneto your package's README, use the codes available below.
You may also use Shields.io to create a custom badge linking to https://www.jsdocs.io/package/execa.
- Markdown[](https://www.jsdocs.io/package/execa)
- HTML<a href="https://www.jsdocs.io/package/execa"><img src="https://img.shields.io/badge/jsDocs.io-reference-blue" alt="jsDocs.io"></a>
- Updated .
Package analyzed in 4236 ms. - Missing or incorrect documentation? Open an issue for this package.
