execa

  • Version 9.5.1
  • Published
  • 324 kB
  • 12 dependencies
  • MIT license

Install

npm i execa
yarn add execa
pnpm add execa

Overview

Process execution for humans

Index

Variables

variable $

const $: ExecaScriptMethod<{}>;
  • Same as execa() but using script-friendly default options.

    When command is a template string, it includes both the file and its arguments.

    $(options) can be used to return a new instance of this method but with different default options. Consecutive calls are merged to previous ones.

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

    Returns

    A ResultPromise that is both: - the subprocess. - a Promise either resolving with its successful result, or rejecting with its error.

    Throws

    ExecaError

    Example 1

    Basic

    import {$} from 'execa';
    const branch = await $`git branch --show-current`;
    await $`dep deploy --branch=${branch}`;

    Example 2

    Verbose mode

    $ node build.js
    Building 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 command is a template string, it includes both the file and its arguments.

    execa(options) can be used to return a new instance of this method but with different default options. 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 file on execution.

    Returns

    A ResultPromise that is both: - the subprocess. - a Promise either resolving with its successful result, or rejecting with its error.

    Throws

    ExecaError

    Example 1

    Simple syntax

    import {execa} from 'execa';
    const {stdout} = await execa`npm run build`;
    // Print command's output
    console.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 eslint

    await 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, interleaved
    console.log(all);

    Example 6

    Programmatic + terminal output

    const {stdout} = await execa({stdout: ['pipe', 'inherit']})`npm run build`;
    // stdout is also printed to the terminal
    console.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.txt
    await execa({stdin: {file: 'input.txt'}})`npm run build`;

    Example 9

    File output

    // Similar to: npm run build > output.txt
    await 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 lines
    console.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 number
    const 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.js
    import {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.js
    import {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.js
    import {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.js
    import {getOneMessage} from 'execa';
    const ipcInput = await getOneMessage();

    Example 17

    Any output type

    // main.js
    import {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.js
    import {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.js
    import {execaNode} from 'execa';
    const controller = new AbortController();
    setTimeout(() => {
    controller.abort();
    }, 5000);
    await execaNode({
    cancelSignal: controller.signal,
    gracefulCancel: true,
    })`build.js`;

    // build.js
    import {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 command
    spawn unknown ENOENT
    at ...
    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 ENOENT
    at ...
    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 Winston
    const 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. command is a string that includes both the file and its arguments.

    When command is a template string, it includes both the file and its arguments.

    execaCommand(options) can be used to return a new instance of this method but with different default options. 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 ResultPromise that is both: - the subprocess. - a Promise either resolving with its successful result, or rejecting with its error.

    Throws

    ExecaError

    Example 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 command is a template string, it includes both the file and its arguments.

    execaCommandSync(options) can be used to return a new instance of this method but with different default options. Consecutive calls are merged to previous ones.

    Returns a subprocess result or throws an error. The subprocess is not returned: its methods and properties are not available.

    Parameter command

    The program/script to execute and its arguments.

    Returns

    SyncResult

    Throws

    ExecaSyncError

    Example 1

    import {execaCommandSync} from 'execa';
    for (const commandAndArguments of getReplLine()) {
    execaCommandSync(commandAndArguments);
    }

variable execaNode

const execaNode: ExecaNodeMethod<{}>;
  • Same as execa() but using the node: true option. Executes a Node.js file using node scriptPath ...arguments.

    When command is a template string, it includes both the file and its arguments.

    execaNode(options) can be used to return a new instance of this method but with different default options. 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 scriptPath on execution.

    Returns

    A ResultPromise that is both: - the subprocess. - a Promise either resolving with its successful result, or rejecting with its error.

    Throws

    ExecaError

    Example 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 result or throws an error. The subprocess is not returned: its methods and properties are not available.

    When command is a template string, it includes both the file and its arguments.

    execaSync(options) can be used to return a new instance of this method but with different default options. 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 file on execution.

    Returns

    SyncResult

    Throws

    ExecaSyncError

    Example 1

    import {execaSync} from 'execa';
    const {stdout} = execaSync`npm run build`;
    // Print command's output
    console.log(stdout);

Functions

function getCancelSignal

getCancelSignal: () => Promise<AbortSignal>;
  • Retrieves the [AbortSignal](https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal) shared by the cancelSignal option.

    This can only be called inside a subprocess. This requires the gracefulCancel option to be true.

function getEachMessage

getEachMessage: (
getEachMessageOptions?: GetEachMessageOptions
) => AsyncIterableIterator<Message>;
  • Iterate over each message from the parent process.

    This requires the ipc option to be true. The type of message depends on the serialization option.

function getOneMessage

getOneMessage: (
getOneMessageOptions?: GetOneMessageOptions<Options['serialization']>
) => Promise<Message>;
  • Receive a single message from the parent process.

    This requires the ipc option to be true. The type of message depends on the serialization option.

function parseCommandString

parseCommandString: (command: string) => string[];
  • Split a command string 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 message to the parent process.

    This requires the ipc option to be true. The type of message depends on the serialization option.

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 reject option 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 reject option 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 using execa(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 using execaNode(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() and getEachMessage().

          This requires the ipc option to be true. The type of message depends on the serialization option.

        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 only stdout, stderr, all (both stdout and stderr), ipc, fd3, etc.

          Example 1

          // Same value for stdout and stderr
          await execa({verbose: 'full'})`npm run build`;
          // Different values for stdout and stderr
          await 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 ExecaError instead.

        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 Promise either resolving with its successful result, or rejecting with its error.

        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_process instance](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 only stdout, stderr, all (both stdout and stderr), ipc, fd3, etc.

                  Example 1

                  // Same value for stdout and stderr
                  execaSync({verbose: 'full'})`npm run build`;
                  // Different values for stdout and stderr
                  execaSync({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 ExecaError instead.

                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 verbose option and execaSync().

                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 verbose option and execa().

                Package Files (14)

                Dependencies (12)

                Dev Dependencies (13)

                Peer Dependencies (0)

                No peer dependencies.

                Badge

                To add a badge like this onejsDocs.io badgeto 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
                  [![jsDocs.io](https://img.shields.io/badge/jsDocs.io-reference-blue)](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>