execa

  • Version 6.0.0
  • Published
  • 56.7 kB
  • 9 dependencies
  • MIT license

Install

npm i execa
yarn add execa
pnpm add execa

Overview

Process execution for humans

Index

Functions

function execa

execa: {
(
file: string,
arguments?: readonly string[],
options?: Options
): ExecaChildProcess;
(file: string, arguments?: readonly string[], options?: Options<null>): any;
(file: string, options?: Options<string>): any;
(file: string, options?: Options<null>): any;
};
  • Execute a file.

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

    Parameter file

    The program/script to execute.

    Parameter arguments

    Arguments to pass to file on execution.

    Returns

    A [child_process instance](https://nodejs.org/api/child_process.html#child_process_class_childprocess), which is enhanced to also be a Promise for a result Object with stdout and stderr properties.

    Example 1

    import {execa} from 'execa';
    const {stdout} = await execa('echo', ['unicorns']);
    console.log(stdout);
    //=> 'unicorns'
    // 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
    }
    // Pipe the child process stdout to the current stdout
    execa('echo', ['unicorns']).stdout.pipe(process.stdout);

function execaCommand

execaCommand: {
(command: string, options?: Options): ExecaChildProcess;
(command: string, options?: Options<null>): any;
};
  • Same as execa() except both file and arguments are specified in a single command string. For example, execa('echo', ['unicorns']) is the same as execaCommand('echo unicorns').

    If the file or an argument contains spaces, they must be escaped with backslashes. This matters especially if command is not a constant but a variable, for example with __dirname or process.cwd(). Except for spaces, no escaping/quoting is needed.

    The shell option must be used if the command uses shell-specific features (for example, && or ||), as opposed to being a simple file followed by its arguments.

    Parameter command

    The program/script to execute and its arguments.

    Returns

    A [child_process instance](https://nodejs.org/api/child_process.html#child_process_class_childprocess), which is enhanced to also be a Promise for a result Object with stdout and stderr properties.

    Example 1

    import {execaCommand} from 'execa';
    const {stdout} = await execaCommand('echo unicorns');
    console.log(stdout);
    //=> 'unicorns'

function execaCommandSync

execaCommandSync: {
(command: string, options?: SyncOptions): ExecaSyncReturnValue;
(command: string, options?: SyncOptions<null>): ExecaSyncReturnValue<Buffer>;
};
  • Same as execaCommand() but synchronous.

    Parameter command

    The program/script to execute and its arguments.

    Returns

    A result Object with stdout and stderr properties.

function execaNode

execaNode: {
(
scriptPath: string,
arguments?: readonly string[],
options?: NodeOptions
): ExecaChildProcess;
(
scriptPath: string,
arguments?: readonly string[],
options?: Options<null>
): any;
(scriptPath: string, options?: Options<string>): any;
(scriptPath: string, options?: Options<null>): any;
};
  • Execute a Node.js script as a child process.

    Same as execa('node', [scriptPath, ...arguments], options) except (like [child_process#fork()](https://nodejs.org/api/child_process.html#child_process_child_process_fork_modulepath_args_options)): - the current Node version and options are used. This can be overridden using the nodePath and nodeArguments options. - the shell option cannot be used - an extra channel [ipc](https://nodejs.org/api/child_process.html#child_process_options_stdio) is passed to [stdio](#stdio)

    Parameter scriptPath

    Node.js script to execute.

    Parameter arguments

    Arguments to pass to scriptPath on execution.

    Returns

    A [child_process instance](https://nodejs.org/api/child_process.html#child_process_class_childprocess), which is enhanced to also be a Promise for a result Object with stdout and stderr properties.

function execaSync

execaSync: {
(
file: string,
arguments?: readonly string[],
options?: SyncOptions
): ExecaSyncReturnValue;
(
file: string,
arguments?: readonly string[],
options?: SyncOptions<null>
): ExecaSyncReturnValue<Buffer>;
(file: string, options?: SyncOptions<string>): ExecaSyncReturnValue<string>;
(file: string, options?: SyncOptions<null>): ExecaSyncReturnValue<Buffer>;
};
  • Execute a file synchronously.

    This method throws an Error if the command fails.

    Parameter file

    The program/script to execute.

    Parameter arguments

    Arguments to pass to file on execution.

    Returns

    A result Object with stdout and stderr properties.

Interfaces

interface CommonOptions

interface CommonOptions<EncodingType> {}

    property all

    readonly all?: boolean;
    • Add an .all property on the promise and the resolved value. The property contains the output of the process with stdout and stderr interleaved.

      false

    property argv0

    readonly argv0?: string;
    • Explicitly set the value of argv[0] sent to the child process. This will be set to command or file if not specified.

    property buffer

    readonly buffer?: boolean;
    • 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.

      true

    property cleanup

    readonly cleanup?: boolean;
    • Kill the spawned process when the parent process exits unless either: - the spawned process is [detached](https://nodejs.org/api/child_process.html#child_process_options_detached) - the parent process is terminated abruptly, for example, with SIGKILL as opposed to SIGTERM or a normal exit

      true

    property cwd

    readonly cwd?: string;
    • Current working directory of the child process.

      process.cwd()

    property detached

    readonly detached?: boolean;
    • Prepare child to run independently of its parent process. Specific behavior [depends on the platform](https://nodejs.org/api/child_process.html#child_process_options_detached).

      false

    property encoding

    readonly encoding?: EncodingType;
    • 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.

      'utf8'

    property env

    readonly env?: NodeJS.ProcessEnv;
    • Environment key-value pairs. Extends automatically from process.env. Set extendEnv to false if you don't want this.

      process.env

    property execPath

    readonly execPath?: string;
    • 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](https://github.com/ehmicky/get-node) to run a specific Node.js version in a child process.

      process.execPath

    property extendEnv

    readonly extendEnv?: boolean;
    • Set to false if you don't want to extend the environment variables when providing the env property.

      true

    property gid

    readonly gid?: number;
    • Sets the group identity of the process.

    property killSignal

    readonly killSignal?: string | number;
    • Signal value to be used when the spawned process will be killed.

      'SIGTERM'

    property localDir

    readonly localDir?: string;
    • Preferred path to find locally installed binaries in (use with preferLocal).

      process.cwd()

    property maxBuffer

    readonly maxBuffer?: number;
    • Largest amount of data in bytes allowed on stdout or stderr. Default: 100 MB.

      100_000_000

    property preferLocal

    readonly preferLocal?: boolean;
    • Prefer locally installed binaries when looking for a binary to execute.

      If you $ npm install foo, you can then execa('foo').

      false

    property reject

    readonly reject?: boolean;
    • Setting this to false resolves the promise with the error instead of rejecting it.

      true

    property serialization

    readonly serialization?: 'json' | 'advanced';
    • 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()](https://nodejs.org/api/v8.html#v8_v8_serialize_value)

      Requires Node.js 13.2.0 or later.

      [More info.](https://nodejs.org/api/child_process.html#child_process_advanced_serialization)

      'json'

    property shell

    readonly shell?: boolean | string;
    • 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.

      false

    property stderr

    readonly stderr?: StdioOption;
    • Same options as [stdio](https://nodejs.org/dist/latest-v6.x/docs/api/child_process.html#child_process_options_stdio).

      'pipe'

    property stdin

    readonly stdin?: StdioOption;
    • Same options as [stdio](https://nodejs.org/dist/latest-v6.x/docs/api/child_process.html#child_process_options_stdio).

      'pipe'

    property stdio

    readonly stdio?: 'pipe' | 'ignore' | 'inherit' | readonly StdioOption[];
    • Child's [stdio](https://nodejs.org/api/child_process.html#child_process_options_stdio) configuration.

      'pipe'

    property stdout

    readonly stdout?: StdioOption;
    • Same options as [stdio](https://nodejs.org/dist/latest-v6.x/docs/api/child_process.html#child_process_options_stdio).

      'pipe'

    property stripFinalNewline

    readonly stripFinalNewline?: boolean;
    • Strip the final [newline character](https://en.wikipedia.org/wiki/Newline) from the output.

      true

    property timeout

    readonly timeout?: number;
    • 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.

      0

    property uid

    readonly uid?: number;
    • Sets the user identity of the process.

    property windowsHide

    readonly windowsHide?: boolean;
    • On Windows, do not create a new console window. Please note this also prevents CTRL-C [from working](https://github.com/nodejs/node/issues/29837) on Windows.

      true

    property windowsVerbatimArguments

    readonly windowsVerbatimArguments?: boolean;
    • 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.

      false

    interface ExecaChildPromise

    interface ExecaChildPromise<StdoutErrorType> {}

      property all

      all?: ReadableStream;
      • Stream combining/interleaving [stdout](https://nodejs.org/api/child_process.html#child_process_subprocess_stdout) and [stderr](https://nodejs.org/api/child_process.html#child_process_subprocess_stderr).

        This is undefined if either: - the all option is false (the default value) - both stdout and stderr options are set to ['inherit', 'ipc', Stream or integer](https://nodejs.org/dist/latest-v6.x/docs/api/child_process.html#child_process_options_stdio)

      method cancel

      cancel: () => void;
      • Similar to [childProcess.kill()](https://nodejs.org/api/child_process.html#child_process_subprocess_kill_signal). This is preferred when cancelling the child process execution as the error is more descriptive and [childProcessResult.isCanceled](#iscanceled) is set to true.

      method catch

      catch: <ResultType = never>(
      onRejected?: (
      reason: ExecaError<StdoutErrorType>
      ) => ResultType | PromiseLike<ResultType>
      ) => Promise<ExecaReturnValue<StdoutErrorType> | ResultType>;

        method kill

        kill: (signal?: string, options?: KillOptions) => void;
        • Same as the original [child_process#kill()](https://nodejs.org/api/child_process.html#child_process_subprocess_kill_signal), except if signal is SIGTERM (the default value) and the child process is not terminated after 5 seconds, force it by sending SIGKILL.

        interface ExecaError

        interface ExecaError<StdoutErrorType = string>
        extends ExecaSyncError<StdoutErrorType> {}

          property all

          all?: StdoutErrorType;
          • The output of the process with stdout and stderr interleaved.

            This is undefined if either: - the all option is false (default value) - execaSync() was used

          property isCanceled

          isCanceled: boolean;
          • Whether the process was canceled.

          interface ExecaReturnBase

          interface ExecaReturnBase<StdoutStderrType> {}

            property command

            command: 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().

            property escapedCommand

            escapedCommand: 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().

            property exitCode

            exitCode: number;
            • The numeric exit code of the process that was run.

            property failed

            failed: boolean;
            • Whether the process failed to run.

            property killed

            killed: boolean;
            • Whether the process was killed.

            property signal

            signal?: string;
            • 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.

            property signalDescription

            signalDescription?: string;
            • 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.

            property stderr

            stderr: StdoutStderrType;
            • The output of the process on stderr.

            property stdout

            stdout: StdoutStderrType;
            • The output of the process on stdout.

            property timedOut

            timedOut: boolean;
            • Whether the process timed out.

            interface ExecaReturnValue

            interface ExecaReturnValue<StdoutErrorType = string>
            extends ExecaSyncReturnValue<StdoutErrorType> {}
            • 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: - its exit code is not 0 - it was killed with a signal - timing out - being canceled - there's not enough memory or there are already too many child processes

            property all

            all?: StdoutErrorType;
            • The output of the process with stdout and stderr interleaved.

              This is undefined if either: - the all option is false (default value) - execaSync() was used

            property isCanceled

            isCanceled: boolean;
            • Whether the process was canceled.

            interface ExecaSyncError

            interface ExecaSyncError<StdoutErrorType = string>
            extends Error,
            ExecaReturnBase<StdoutErrorType> {}

              property message

              message: 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.

              property originalMessage

              originalMessage?: string;
              • 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.

              property shortMessage

              shortMessage: string;
              • This is the same as the message property except it does not include the child process stdout/stderr.

              interface ExecaSyncReturnValue

              interface ExecaSyncReturnValue<StdoutErrorType = string>
              extends ExecaReturnBase<StdoutErrorType> {}

                interface KillOptions

                interface KillOptions {}

                  property forceKillAfterTimeout

                  forceKillAfterTimeout?: number | false;
                  • Milliseconds to wait for the child process to terminate before sending SIGKILL.

                    Can be disabled with false.

                    5000

                  interface NodeOptions

                  interface NodeOptions<EncodingType = string> extends Options<EncodingType> {}

                    property nodeOptions

                    readonly nodeOptions?: string[];
                    • List of [CLI options](https://nodejs.org/api/cli.html#cli_options) passed to the Node.js executable.

                      process.execArgv

                    property nodePath

                    readonly nodePath?: string;
                    • The Node.js executable to use.

                      process.execPath

                    interface Options

                    interface Options<EncodingType = string> extends CommonOptions<EncodingType> {}

                      property input

                      readonly input?: string | Buffer | ReadableStream;
                      • Write some input to the stdin of your binary.

                      interface SyncOptions

                      interface SyncOptions<EncodingType = string> extends CommonOptions<EncodingType> {}

                        property input

                        readonly input?: string | Buffer;
                        • Write some input to the stdin of your binary.

                        Type Aliases

                        type ExecaChildProcess

                        type ExecaChildProcess<StdoutErrorType = string> = ChildProcess &
                        ExecaChildPromise<StdoutErrorType> &
                        Promise<ExecaReturnValue<StdoutErrorType>>;

                          type StdioOption

                          type StdioOption =
                          | 'pipe'
                          | 'ipc'
                          | 'ignore'
                          | 'inherit'
                          | Stream
                          | number
                          | undefined;

                            Package Files (1)

                            Dependencies (9)

                            Dev Dependencies (9)

                            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>