### Install Local Binary Source: https://github.com/sindresorhus/execa/blob/main/docs/environment.md Example of installing a local binary using npm. This is a prerequisite for executing local binaries with Execa. ```sh $ npm install -D eslint ``` -------------------------------- ### Execute Script with Shebang on Windows Source: https://github.com/sindresorhus/execa/blob/main/docs/windows.md Execa supports shebangs on Windows by internally converting them to a `node` command. This example shows how to execute a script that starts with `#!/usr/bin/env node`. ```javascript import {execa} from 'execa'; // If script.js starts with #!/usr/bin/env node await execa`./script.js`; // Then, the above is a shortcut for: await execa`node ./script.js`; ``` -------------------------------- ### Execute Local Binaries with Execa Source: https://github.com/sindresorhus/execa/blob/main/docs/bash.md Use the `preferLocal: true` option with Execa to ensure that locally installed binaries (e.g., via npm/yarn) are preferred over globally installed ones. ```bash npx tsc --version ``` ```javascript // zx await $({preferLocal: true})`tsc --version`; ``` ```javascript // Execa await $({preferLocal: true})`tsc --version`; ``` -------------------------------- ### Example Script for Interleaved Output Source: https://github.com/sindresorhus/execa/blob/main/docs/output.md A simple Node.js script demonstrating how console logs and errors might be interleaved when 'all: true' is used. ```javascript // example.js console.log('1'); // writes to stdout console.error('2'); // writes to stderr console.log('3'); // writes to stdout ``` -------------------------------- ### Execute local binaries Source: https://github.com/sindresorhus/execa/blob/main/readme.md Run binaries installed in the local node_modules directory by setting preferLocal to true. ```sh $ npm install -D eslint ``` ```js await execa({preferLocal: true})`eslint`; ``` -------------------------------- ### Prompt for User Input Source: https://github.com/sindresorhus/execa/blob/main/docs/bash.md Use this to get user input in a script. Execa's input method is an alternative to the built-in question prompt in zx. ```bash read -p "Question? " answer ``` ```javascript // zx const answer = await question('Question? '); ``` ```javascript // Execa import input from '@inquirer/input'; const answer = await input({message: 'Question?'}); ``` -------------------------------- ### Use Web Streams for Input/Output Source: https://context7.com/sindresorhus/execa/llms.txt Utilize web streams for subprocess input and output. This example shows fetching a response body as input for a command. ```javascript import {execa} from 'execa'; // Fetch response body as input const response = await fetch('https://example.com'); await execa({stdin: response.body})`sort`; ``` -------------------------------- ### Configure stdio for all file descriptors Source: https://github.com/sindresorhus/execa/blob/main/docs/api.md Use the `stdio` option to configure stdin, stdout, and stderr simultaneously. It accepts an array where each element corresponds to a file descriptor. For example, `['ignore', 'pipe', 'pipe']` is equivalent to `{stdin: 'ignore', stdout: 'pipe', stderr: 'pipe'}`. You can also use shortcuts or define additional file descriptors. ```typescript execa('foo', { stdio: ['ignore', 'pipe', 'pipe'] }); ``` -------------------------------- ### Combine Multiple Input Sources Source: https://github.com/sindresorhus/execa/blob/main/docs/input.md Provide input to the subprocess from multiple sources simultaneously by passing an array to the `stdin` option. This example combines terminal input inheritance with file input. ```javascript await execa({stdin: ['inherit', {file: 'input.txt'}]})`npm run scaffold`; ``` -------------------------------- ### Using Web CompressionStream with Transform Source: https://github.com/sindresorhus/execa/blob/main/docs/transform.md Utilize web TransformStream API, such as CompressionStream('gzip'), for transforms. Set 'encoding' to 'buffer' for binary output. This example compresses stdout using gzip. ```javascript const {stdout} = await execa({ stdout: new CompressionStream('gzip'), encoding: 'buffer', })`npm run build`; console.log(stdout); // `stdout` is compressed with gzip ``` -------------------------------- ### Use Node.js Streams for Input/Output Source: https://context7.com/sindresorhus/execa/llms.txt Integrate Node.js streams for subprocess input and output. Examples include using file streams for both reading and writing. ```javascript import {createReadStream, createWriteStream} from 'node:fs'; import {once} from 'node:events'; import {execa} from 'execa'; // File stream as input const readable = createReadStream('input.txt'); await once(readable, 'open'); await execa({stdin: readable})`npm run scaffold`; // File stream as output const writable = createWriteStream('output.txt'); await once(writable, 'open'); await execa({stdout: writable})`npm run build`; ``` -------------------------------- ### Using Node.js zlib.createGzip with Transform Source: https://github.com/sindresorhus/execa/blob/main/docs/transform.md Integrate Node.js Transform streams, like zlib.createGzip, as transforms. Ensure 'encoding' is set to 'buffer' when dealing with binary data. This example compresses stdout using gzip. ```javascript import {createGzip} from 'node:zlib'; import {execa} from 'execa'; const {stdout} = await execa({ stdout: {transform: createGzip()}, encoding: 'buffer', })`npm run build`; console.log(stdout); // `stdout` is compressed with gzip ``` -------------------------------- ### Manual Shell-Specific Quoting Source: https://github.com/sindresorhus/execa/blob/main/docs/windows.md When using a shell, manual shell-specific quoting is required. This example shows how to quote an argument with spaces for `cmd.exe` on Windows and `sh` on Unix. ```javascript if (isWindows) { await execa({shell: true})`npm run ${'"task with space"'}`; } else { await execa({shell: true})`npm run ${'\'task with space\''}`; } ``` -------------------------------- ### Implement custom logging for Execa commands Source: https://github.com/sindresorhus/execa/blob/main/readme.md Configure Execa to use a custom logging function, allowing you to direct verbose output to files or other destinations using libraries like Winston. This example logs to 'logs.txt'. ```javascript 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`; ``` -------------------------------- ### Execute Shell Commands with $ Source: https://github.com/sindresorhus/execa/blob/main/docs/scripts.md Use the `$` operator for executing shell commands in script files. It includes script-friendly default options like `stdin: 'inherit'` and `preferLocal: true`. This example demonstrates piping output and running multiple commands concurrently. ```javascript 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}`; ``` -------------------------------- ### Executing a Build Command Source: https://github.com/sindresorhus/execa/blob/main/docs/bash.md Demonstrates how to execute a build command using Execa, similar to zx's approach with global variables. ```javascript // zx await $`npm run build`; ``` ```javascript // Execa import {$} from 'execa'; await $`npm run build`; ``` -------------------------------- ### Basic Command Execution Source: https://github.com/sindresorhus/execa/blob/main/docs/bash.md Illustrates the execution of a simple command, showing similarities between Bash, zx, and Execa. ```bash # Bash npm run build ``` ```javascript // zx await $`npm run build`; ``` ```javascript // Execa await $`npm run build`; ``` -------------------------------- ### Get process PID Source: https://github.com/sindresorhus/execa/blob/main/docs/bash.md Retrieves the process ID of a spawned subprocess. ```bash # Bash npm run build & echo $! ``` ```javascript // Execa const {pid} = $`npm run build`; ``` -------------------------------- ### Execute commands with nano-spawn Source: https://github.com/sindresorhus/execa/blob/main/docs/small.md Use this lightweight alternative when package size is a constraint and advanced Execa features are not required. ```js import spawn from 'nano-spawn'; const result = await spawn('npm', ['run', 'build']); ``` -------------------------------- ### Run Node.js files with Execa Source: https://github.com/sindresorhus/execa/blob/main/docs/node.md Demonstrates different ways to execute a Node.js file using execaNode or the node option. ```js 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`; ``` -------------------------------- ### Get current filename Source: https://github.com/sindresorhus/execa/blob/main/docs/bash.md Retrieves the name of the current script file. ```bash # Bash echo "$(basename "$0")" ``` ```javascript // zx await $`echo ${__filename}`; ``` ```javascript // Execa await $`echo ${import.meta.filename}`; ``` -------------------------------- ### Execute Command with Array Syntax Source: https://github.com/sindresorhus/execa/blob/main/docs/execution.md Use the array syntax for basic command execution. Ensure 'execa' is imported. ```javascript import {execa} from 'execa'; await execa('npm', ['run', 'build']); ``` -------------------------------- ### execa(file, arguments?, options?) Source: https://github.com/sindresorhus/execa/blob/main/docs/api.md Executes a command using the specified file and arguments. ```APIDOC ## execa(file, arguments?, options?) ### Description Executes a command using `file ...arguments`. ### Parameters #### Path Parameters - **file** (string | URL) - Required - The file to execute. - **arguments** (string[]) - Optional - Arguments to pass to the file. - **options** (Options) - Optional - Configuration options for the execution. ### Response - **ResultPromise** (ResultPromise) - Returns a promise that resolves to the execution result. ``` -------------------------------- ### Handle command timeouts Source: https://github.com/sindresorhus/execa/blob/main/docs/bash.md Demonstrates how to enforce a timeout on a command execution. ```bash timeout 1 sleep 2 echo $? ``` ```javascript // zx await $`sleep 2`.timeout('1ms'); ``` ```javascript // Execa await $({timeout: 1})`sleep 2`; ``` -------------------------------- ### Execute a command with arguments Source: https://github.com/sindresorhus/execa/blob/main/docs/api.md Use `execa` to run a command with specified arguments. Ensure correct syntax for file paths and arguments. ```javascript execa("node", ["--version"]) ``` -------------------------------- ### Object Mode Transform for JSON Parsing Source: https://context7.com/sindresorhus/execa/llms.txt Process subprocess output as objects using `objectMode: true`. This example parses JSON lines from a subprocess. ```javascript import {execa} from 'execa'; // Parse JSON lines const parseJson = function * (line) { yield JSON.parse(line); }; const {stdout} = await execa({ stdout: {transform: parseJson, objectMode: true} })`node jsonlines-output.js`; for (const data of stdout) { console.log(data); // {...object} } // Stringify objects for input const stringifyJson = function * (line) { yield JSON.stringify(line); }; const input = [{event: 'example'}, {event: 'otherExample'}]; await execa({ stdin: [input, {transform: stringifyJson, objectMode: true}] })`node jsonlines-input.js`; ``` -------------------------------- ### Test Current Package's Binary with get-bin-path Source: https://github.com/sindresorhus/execa/blob/main/docs/environment.md Combine Execa with `get-bin-path` to reliably test the current package's binary, ensuring the `bin` field in `package.json` is correctly configured. ```javascript import {execa} from 'execa'; import {getBinPath} from 'get-bin-path'; const binPath = await getBinPath(); await execa(binPath); ``` -------------------------------- ### Use Web streams Source: https://github.com/sindresorhus/execa/blob/main/docs/bash.md Uses web streams as input for command execution. ```javascript // zx does not support web streams ``` ```javascript // Execa const response = await fetch('https://example.com'); await $({stdin: response.body})`npm run build`; ``` -------------------------------- ### Filtering Lines with Transforms Source: https://github.com/sindresorhus/execa/blob/main/docs/transform.md A transform can filter lines by not yielding any output for specific input lines. This example filters out lines containing the word 'secret'. ```javascript const transform = function * (line) { if (!line.includes('secret')) { yield line; } }; const {stdout} = await execa({stdout: transform})`echo ${'This is a secret'}`; console.log(stdout); // '' ``` -------------------------------- ### execaNode(scriptPath, arguments?, options?) Source: https://github.com/sindresorhus/execa/blob/main/docs/api.md Executes a Node.js file using the node runtime. ```APIDOC ## execaNode(scriptPath, arguments?, options?) ### Description Executes a Node.js file using `node scriptPath ...arguments`. This is the preferred method when executing Node.js files. ### Parameters #### Path Parameters - **scriptPath** (string | URL) - Required - The path to the Node.js script. - **arguments** (string[]) - Optional - Arguments to pass to the script. - **options** (Options) - Optional - Configuration options for the execution. ### Response - **ResultPromise** (ResultPromise) - Returns a promise that resolves to the execution result. ``` -------------------------------- ### Handle Subprocess Failure with ExecaError Source: https://github.com/sindresorhus/execa/blob/main/docs/errors.md When a subprocess fails, the promise returned by execa() is rejected with an ExecaError. This example shows how to catch this error and check the `failed` property. ```javascript import {execa, ExecaError} from 'execa'; try { const result = await execa`npm run build`; console.log(result.failed); // false } catch (error) { if (error instanceof ExecaError) { console.error(error.failed); // true } } ``` -------------------------------- ### Create Reusable Execa Instance with Shared Options Source: https://github.com/sindresorhus/execa/blob/main/docs/execution.md Create a reusable Execa instance with predefined options. This instance can then be used to execute multiple commands with the same options. ```javascript const timedExeca = execa({timeout: 5000}); await timedExeca('npm', ['run', 'build']); await timedExeca`npm run test`; ``` -------------------------------- ### Enable Verbose Mode Source: https://github.com/sindresorhus/execa/blob/main/docs/bash.md Configures command execution to display output in real-time. ```bash set -v npm run build set +v ``` ```javascript // zx await $`npm run build`.verbose(); ``` ```javascript // Execa await $({verbose: 'full'})`npm run build`; ``` -------------------------------- ### Inactivity Timeout with Debouncing Source: https://github.com/sindresorhus/execa/blob/main/docs/termination.md Terminate a subprocess if it remains inactive (no output to stdout/stderr) for a specified duration. This example uses debouncing logic to cancel the operation after a minute of inactivity. ```javascript import {execa} from 'execa'; import debounceFn from 'debounce-fn'; // 1 minute const wait = 60_000; const getInactivityOptions = () => { const controller = new AbortController(); const cancelSignal = controller.signal; // Delay and debounce `cancelSignal` each time `controller.abort()` is called const scheduleAbort = debounceFn(controller.abort.bind(controller), {wait}); const onOutput = { * transform(data) { // When anything is printed, debounce `controller.abort()` scheduleAbort(); // Keep the output as is yield data; }, // Debounce even if the output does not include any newline binary: true, }; // Start debouncing scheduleAbort(); return { cancelSignal, stdout: onOutput, stderr: onOutput, }; }; const options = getInactivityOptions(); await execa(options)`npm run build`; ``` -------------------------------- ### Execute Local Binary with Custom Local Directory Source: https://github.com/sindresorhus/execa/blob/main/docs/environment.md Specify a custom directory to search for local binaries using the `localDir` option in conjunction with `preferLocal`. ```javascript await execa({preferLocal: true, localDir: '/path/to/dir'})`eslint`; ``` -------------------------------- ### Use stdio shortcut options Source: https://github.com/sindresorhus/execa/blob/main/docs/output.md Apply a single stdio configuration to stdin, stdout, and stderr simultaneously. ```js await execa({stdio: 'ignore'})`npm run build`; // Same as: await execa({stdin: 'ignore', stdout: 'ignore', stderr: 'ignore'})`npm run build`; ``` -------------------------------- ### Sharing State Between Transform Calls Source: https://github.com/sindresorhus/execa/blob/main/docs/transform.md Generator functions used as transforms can maintain state across multiple calls. This example uses a 'count' variable to prefix each yielded line with its line number. ```javascript let count = 0; // Prefix line number const transform = function * (line) { yield `[${count++}] ${line}`; }; ``` -------------------------------- ### options.all Source: https://github.com/sindresorhus/execa/blob/main/docs/api.md Enables capturing all output (stdout and stderr) into a single stream and result property. ```APIDOC ## options.all ### Description Add a [`subprocess.all`](#subprocessall) stream and a [`result.all`](#resultall) property. [More info.](output.md#interleaved-output) ### Type `boolean` ### Default `false` ``` -------------------------------- ### Basic Transform with Generator Function Source: https://github.com/sindresorhus/execa/blob/main/docs/transform.md Use a generator function to transform each line of stdout. The transform function receives a line and yields modified lines. This example prefixes each line with 'INFO' or 'ERROR'. ```javascript import {execa} from 'execa'; const transform = function * (line) { const prefix = line.includes('error') ? 'ERROR' : 'INFO'; yield `${prefix}: ${line}`; }; const {stdout} = await execa({stdout: transform})`echo HELLO`; console.log(stdout); // INFO: HELLO ``` -------------------------------- ### Execute Local Binary with preferLocal Option Source: https://github.com/sindresorhus/execa/blob/main/docs/environment.md Use the `preferLocal` option to automatically execute local binaries found in `./node_modules/.bin` or parent directories. ```javascript await execa({preferLocal: true})`eslint`; ``` -------------------------------- ### Finalizing Output with a Final Generator Source: https://github.com/sindresorhus/execa/blob/main/docs/transform.md A 'final' generator function can be used to yield additional lines after all input lines have been processed. This example counts the number of processed lines and yields the total count at the end. ```javascript let count = 0; const transform = function * (line) { count += 1; yield line; }; const final = function * () { yield `Number of lines: ${count}`; }; const {stdout} = await execa({stdout: {transform, final}})`npm run build`; console.log(stdout); // Ends with: 'Number of lines: 54' ``` -------------------------------- ### Object Mode Transform for JSON Output Source: https://github.com/sindresorhus/execa/blob/main/docs/transform.md Enable object mode for transforms to yield non-string/Uint8Array values, such as parsed JSON objects. The result will be an array of yielded values. This example parses each line as JSON. ```javascript const transform = function * (line) { yield JSON.parse(line); }; const {stdout} = await execa({stdout: {transform, objectMode: true}})`node jsonlines-output.js`; for (const data of stdout) { console.log(stdout); // {...object} } ``` -------------------------------- ### Execute Local Binary Directly Source: https://github.com/sindresorhus/execa/blob/main/docs/environment.md Execute a local binary by providing its relative path. This is useful when the `preferLocal` option is not used. ```javascript await execa('./node_modules/.bin/eslint'); ``` -------------------------------- ### Execute commands with node:child_process Source: https://github.com/sindresorhus/execa/blob/main/docs/small.md Use the native Node.js module to avoid external dependencies, noting that it lacks many convenience features provided by Execa or nano-spawn. ```js import {execFile} from 'node:child_process'; import {promisify} from 'node:util'; const pExecFile = promisify(execFile); const result = await pExecFile('npm', ['run', 'build']); ``` -------------------------------- ### Object Mode Transform for JSON Input Source: https://github.com/sindresorhus/execa/blob/main/docs/transform.md Use object mode for stdin transforms to send non-string/Uint8Array data, such as JSON objects. The transform function receives values and yields stringified versions. This example sends an array of objects to be stringified. ```javascript const transform = function * (line) { yield JSON.stringify(line); }; const input = [{event: 'example'}, {event: 'otherExample'}]; await execa({stdin: [input, {transform, objectMode: true}]})`node jsonlines-input.js`; ``` -------------------------------- ### Send initial messages to subprocess Source: https://github.com/sindresorhus/execa/blob/main/docs/ipc.md Pass initial data to a subprocess at startup using the ipcInput option. ```javascript // 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`; ``` ```javascript // build.js import {getOneMessage} from 'execa'; const ipcInput = await getOneMessage(); ``` -------------------------------- ### Execute simple commands Source: https://github.com/sindresorhus/execa/blob/main/readme.md Use template literals to execute commands and capture the standard output. ```js import {execa} from 'execa'; const {stdout} = await execa`npm run build`; // Print command's output console.log(stdout); ``` -------------------------------- ### Execute commands with verbose logging Source: https://github.com/sindresorhus/execa/blob/main/readme.md Run commands and observe detailed output by default. This is useful for debugging and understanding the execution flow. ```javascript await execa`npm run build`; await execa`npm run test`; ``` -------------------------------- ### Split output into lines Source: https://github.com/sindresorhus/execa/blob/main/docs/lines.md Use the lines option to receive output as an array of strings instead of a single string. ```js import {execa} from 'execa'; const lines = await execa({lines: true})`npm run build`; console.log(lines.join('\n')); ``` -------------------------------- ### Execa Configuration Options Source: https://github.com/sindresorhus/execa/blob/main/docs/api.md A comprehensive list of available options for configuring subprocess execution in Execa. ```APIDOC ## Execa Options ### options.serialization - **Type**: 'json' | 'advanced' - **Default**: 'advanced' - **Description**: Specify the kind of serialization used for sending messages between subprocesses when using the ipc option. ### options.ipcInput - **Type**: Message - **Description**: Sends an IPC message when the subprocess starts. The subprocess must be a Node.js file. ### options.verbose - **Type**: 'none' | 'short' | 'full' | Function - **Default**: 'none' - **Description**: Configures logging verbosity. 'short' prints command details to stderr; 'full' or a function includes stdout, stderr, and IPC messages. ### options.reject - **Type**: boolean - **Default**: true - **Description**: If false, resolves the promise with the error instead of rejecting it. ### options.timeout - **Type**: number - **Default**: 0 - **Description**: Milliseconds to wait before terminating the subprocess if it exceeds the limit. ### options.cancelSignal - **Type**: AbortSignal - **Description**: Aborts the subprocess using SIGTERM when the signal is triggered. ### options.gracefulCancel - **Type**: boolean - **Default**: false - **Description**: If true, uses the AbortSignal returned by getCancelSignal() instead of SIGTERM for termination. ### options.forceKillAfterDelay - **Type**: number | false - **Default**: 5000 - **Description**: Forcefully kills the subprocess with SIGKILL if it does not exit after termination. ### options.killSignal - **Type**: string | number - **Default**: 'SIGTERM' - **Description**: The signal used to terminate the subprocess. ### options.detached - **Type**: boolean - **Default**: false - **Description**: Runs the subprocess independently from the current process. ### options.cleanup - **Type**: boolean - **Default**: true - **Description**: Kills the subprocess automatically when the current process exits. ### options.uid / options.gid - **Type**: number - **Description**: Sets the user or group identifier for the subprocess. ### options.argv0 - **Type**: string - **Default**: file being executed - **Description**: Sets the value of argv[0] for the subprocess. ### options.windowsHide - **Type**: boolean - **Default**: true - **Description**: On Windows, prevents the creation of a new console window. ### options.windowsVerbatimArguments - **Type**: boolean - **Default**: true if shell is true, false otherwise - **Description**: If false, escapes command arguments on Windows. ``` -------------------------------- ### Provide input to processes Source: https://github.com/sindresorhus/execa/blob/main/readme.md Pass strings, files, or streams as input to the executed process. ```js const getInputString = () => { /* ... */ }; const {stdout} = await execa({input: getInputString()})`sort`; console.log(stdout); ``` ```js // Similar to: npm run build < input.txt await execa({stdin: {file: 'input.txt'}})`npm run build`; ``` -------------------------------- ### Execute a Node.js file Source: https://github.com/sindresorhus/execa/blob/main/docs/api.md Use `execaNode` to execute a Node.js file. This method is preferred for running Node.js scripts. ```javascript execaNode("fixture.js", ["foo", "bar"]) ``` -------------------------------- ### Execute Command with Options (Template String Syntax) Source: https://github.com/sindresorhus/execa/blob/main/docs/execution.md Pass options to influence command execution using the template string syntax. The options object precedes the template string. ```javascript await execa({timeout: 5000})`npm run build`; ``` -------------------------------- ### Template String with No Arguments Source: https://github.com/sindresorhus/execa/blob/main/docs/execution.md Execute a command with no arguments using an empty array in a template string. This is equivalent to calling execa with an empty array. ```javascript await execa`npm run build ${[]}`; // Same as: await execa('npm', ['run', 'build']); ``` -------------------------------- ### Configure Global Options for Execa Commands Source: https://github.com/sindresorhus/execa/blob/main/docs/bash.md Set global options like `verbose: true` for multiple Execa commands by creating a configured Execa instance. This avoids repeating options for each command. ```bash options="timeout 5" $options npm run init $options npm run build $options npm run test ``` ```javascript // zx const $$ = $({verbose: true}); await $$`npm run init`; await $$`npm run build`; await $$`npm run test`; ``` ```javascript // Execa import {$ as $_} from 'execa'; const $ = $_({verbose: true}); await $`npm run init`; await $`npm run build`; await $`npm run test`; ``` -------------------------------- ### Execute Command with Options (Array Syntax) Source: https://github.com/sindresorhus/execa/blob/main/docs/execution.md Pass options to influence command execution using the array syntax. The options object is the third argument. ```javascript await execa('npm', ['run', 'build'], {timeout: 5000}); ``` -------------------------------- ### $ - Script-Friendly Execution Source: https://context7.com/sindresorhus/execa/llms.txt A variant of execa with script-friendly defaults like stdin: 'inherit' and preferLocal: true. ```APIDOC ## $`command` ### Description Executes commands with defaults optimized for scripts, such as inheriting stdin and preferring local binaries. ### Features - **pipe** - Supports piping output to other commands. - **parallel** - Can be used with Promise.all for parallel execution. ``` -------------------------------- ### Configure default options for methods Source: https://github.com/sindresorhus/execa/blob/main/docs/api.md You can create new instances of methods with pre-configured default options. These options are merged with subsequent calls. ```javascript const { execa } = require('execa'); const customExeca = execa.options({ stdin: 'pipe' }); ``` ```javascript const { $ } = require('execa'); const custom$ = $.options({ stdin: 'pipe' }); ``` ```javascript const { execaNode } = require('execa'); const customExecaNode = execaNode.options({ stdin: 'pipe' }); ``` ```javascript const { execaSync } = require('execa'); const customExecaSync = execaSync.options({ stdin: 'pipe' }); ``` ```javascript const { $.sync } = require('execa'); const custom$.sync = $.sync.options({ stdin: 'pipe' }); ``` ```javascript const { $.s } = require('execa'); const custom$.s = $.s.options({ stdin: 'pipe' }); ``` -------------------------------- ### Handle exit codes Source: https://github.com/sindresorhus/execa/blob/main/docs/bash.md Shows how to capture exit codes without throwing errors. ```bash # Bash npm run build echo $? ``` ```javascript // zx const {exitCode} = await $`npm run build`.nothrow(); ``` ```javascript // Execa const {exitCode} = await $({reject: false})`npm run build`; ``` -------------------------------- ### options.lines Source: https://github.com/sindresorhus/execa/blob/main/docs/api.md Configures the output to be split into an array of strings, with each string representing a line. ```APIDOC ## options.lines ### Description Set [`result.stdout`](#resultstdout), [`result.stderr`](#resultstdout), [`result.all`](#resultall) and [`result.stdio`](#resultstdio) as arrays of strings, splitting the subprocess' output into lines. This cannot be used if the [`encoding`](#optionsencoding) option is [binary](binary.md#binary-output). By default, this applies to both `stdout` and `stderr`, but [different values can also be passed](output.md#stdoutstderr-specific-options). [More info.](lines.md#simple-splitting) ### Type `boolean` ### Default `false` ``` -------------------------------- ### options.stdio Source: https://github.com/sindresorhus/execa/blob/main/docs/api.md Configures the standard input, output, and error streams for the subprocess. It can be a string, an array of stream configurations, or a tuple for specific file descriptors. ```APIDOC ## options.stdio ### Description Like the `stdin`, `stdout` and `stderr` options but for all [file descriptors](https://en.wikipedia.org/wiki/File_descriptor) at once. For example, `{stdio: ['ignore', 'pipe', 'pipe']}` is the same as `{stdin: 'ignore', stdout: 'pipe', stderr: 'pipe'}`. A single string can be used [as a shortcut](output.md#shortcut). The array can have more than 3 items, to create [additional file descriptors](output.md#additional-file-descriptors) beyond `stdin`/`stdout`/`stderr`. More info on [available values](output.md), [streaming](streams.md) and [transforms](transform.md). ### Type `string | Array | Iterable | Iterable | AsyncIterable | GeneratorFunction | AsyncGeneratorFunction | {transform: GeneratorFunction | AsyncGeneratorFunction | Duplex | TransformStream}>` (or a tuple of those types) ### Default `pipe` ``` -------------------------------- ### Execute a command using script-friendly defaults Source: https://github.com/sindresorhus/execa/blob/main/docs/api.md The `$` method is preferred for executing multiple commands in a script file, as it uses script-friendly default options. ```javascript $("node", ["--version"]) ``` -------------------------------- ### Running Node.js Scripts Source: https://github.com/sindresorhus/execa/blob/main/docs/bash.md Execa scripts are standard Node.js files and are executed using the `node` command. ```bash # Bash bash file.sh ``` ```javascript // zx zx file.js // or a shebang can be used: // #!/usr/bin/env zx ``` ```javascript // Execa scripts are just regular Node.js files node file.js ``` -------------------------------- ### Configure global verbose mode Source: https://github.com/sindresorhus/execa/blob/main/docs/debugging.md Use the NODE_DEBUG=execa environment variable to default verbose mode to full. ```js // build.js // This is logged by default await execa`npm run build`; // This is not logged await execa({verbose: 'none'})`npm run test`; ``` -------------------------------- ### execaNode - Execute Node.js Files Source: https://context7.com/sindresorhus/execa/llms.txt Executes Node.js files using the current Node.js version and CLI flags, with IPC enabled by default. ```APIDOC ## execaNode(file, [arguments], [options]) ### Description Executes a Node.js script file. ### Options - **nodeOptions** (array) - Optional - CLI flags to pass to the Node.js process. - **nodePath** (string) - Optional - Path to a specific Node.js executable. ``` -------------------------------- ### Handle Binary Output with Execa Source: https://github.com/sindresorhus/execa/blob/main/docs/bash.md Capture binary output from a command using Execa by setting the `encoding` option to `'buffer'`. This is useful for commands that produce non-textual output. ```bash zip -r - input.txt > output.txt ``` ```javascript // zx const stdout = await $`zip -r - input.txt`.buffer(); ``` ```javascript // Execa const {stdout} = await $({encoding: 'buffer'})`zip -r - input.txt`; ``` -------------------------------- ### Asynchronous Execution with TypeScript Source: https://github.com/sindresorhus/execa/blob/main/docs/typescript.md Demonstrates using explicit types for asynchronous process execution with Execa, including IPC and verbose logging. ```ts import { execa as execa_, ExecaError, type ResultPromise, type Result, type Options, type StdinOption, type StdoutStderrOption, type TemplateExpression, type Message, type VerboseObject, type ExecaMethod, } from 'execa'; const execa: ExecaMethod = execa_({preferLocal: true}); const options: Options = { stdin: 'inherit' satisfies StdinOption, stdout: 'pipe' satisfies StdoutStderrOption, stderr: 'pipe' satisfies StdoutStderrOption, timeout: 1000, ipc: true, verbose(verboseLine: string, verboseObject: VerboseObject) { return verboseObject.type === 'duration' ? verboseLine : undefined; }, }; const task: TemplateExpression = 'build'; const message: Message = 'hello world'; try { const subprocess: ResultPromise = execa(options)`npm run ${task}`; await subprocess.sendMessage?.(message); const result: Result = await subprocess; console.log(result.stdout); } catch (error) { if (error instanceof ExecaError) { console.error(error); } } ``` -------------------------------- ### Execute Command with Specific Shell Source: https://github.com/sindresorhus/execa/blob/main/docs/shell.md Use this when you need to execute a command using a specific shell, like Bash. Ensure the shell path is correct for your system. ```javascript import {execa} from 'execa'; await execa({shell: '/bin/bash'})`npm run "$TASK" && npm run test`; ``` -------------------------------- ### options.stdin Configuration Source: https://github.com/sindresorhus/execa/blob/main/docs/api.md Configure the standard input for a subprocess. Supports various data types including strings, streams, file descriptors, and more. ```APIDOC ## options.stdin ### Description How to setup the subprocess' [standard input](https://en.wikipedia.org/wiki/Standard_streams#Standard_input_(stdin)). ### Type `string | number | stream.Readable | ReadableStream | TransformStream | URL | {file: string} | Uint8Array | Iterable | AsyncIterable | GeneratorFunction | AsyncGeneratorFunction | {transform: GeneratorFunction | AsyncGeneratorFunction | Duplex | TransformStream}` (or a tuple of those types) ### Default `'inherit'` with [`$`](#file-arguments-options), `'pipe'` otherwise ### Available Values - `'pipe'` - `'overlapped'` - `'ignore'` - `'inherit'` - File descriptor integer - Node.js `Readable` stream - Web `ReadableStream` - `{ file: 'path' }` object - File URL - `Iterable` (including an array of strings) - `AsyncIterable` - `Uint8Array` - Generator function - `Duplex` or web `TransformStream` ### Example This can be an [array of values](output.md#multiple-targets) such as `['inherit', 'pipe']` or `[fileUrl, 'pipe']`. More info on [available values](input.md), [streaming](streams.md) and [transforms](transform.md). ``` -------------------------------- ### Execute a command using template string syntax Source: https://github.com/sindresorhus/execa/blob/main/docs/api.md Template strings can be used to execute commands, combining the file and arguments into a single string. This syntax supports options. ```javascript execa`node --version` ``` ```javascript $`node --version` ``` ```javascript execaNode`node --version` ``` ```javascript execaSync`node --version` ``` ```javascript $.sync`node --version` ``` ```javascript $.s`node --version` ``` -------------------------------- ### Execute Commands with execa Source: https://context7.com/sindresorhus/execa/llms.txt Use `execa` for asynchronous command execution. It returns a promise with command results. Supports array and template string syntax for commands and arguments. ```javascript import {execa} from 'execa'; // Array syntax const {stdout} = await execa('npm', ['run', 'build']); console.log(stdout); // Template string syntax (recommended) const {stdout: output} = await execa`npm run build`; console.log(output); // With dynamic arguments const task = 'build'; const {stdout: taskOutput} = await execa`npm run ${task}`; // With options const {stdout: timedOutput} = await execa({timeout: 5000})`npm run build`; // Global/shared options const timedExeca = execa({timeout: 5000}); await timedExeca`npm run build`; await timedExeca`npm run test`; ``` -------------------------------- ### Execa Options Source: https://github.com/sindresorhus/execa/blob/main/docs/api.md Overview of the configuration options available for Execa methods. ```APIDOC ## Options _TypeScript:_ [`Options`](typescript.md) or [`SyncOptions`](typescript.md) _Type:_ `object` This lists all options for [`execa()`](#execafile-arguments-options) and the [other methods](#methods). The following options [can specify different values](output.md#stdoutstderr-specific-options) for [`stdout`](#optionsstdout) and [`stderr`](#optionsstderr): [`verbose`](#optionsverbose), [`lines`](#optionslines), [`stripFinalNewline`](#optionsstripfinalnewline), [`buffer`](#optionsbuffer), [`maxBuffer`](#optionsmaxbuffer). ``` -------------------------------- ### Basic Error Handling with Execa Source: https://context7.com/sindresorhus/execa/llms.txt Illustrates how to catch and inspect errors from subprocesses using a `try...catch` block. The `ExecaError` object provides detailed information about the failure, including exit code, signals, and output. ```javascript import {execa, ExecaError} from 'execa'; try { await execa`unknown command`; } catch (error) { if (error instanceof ExecaError) { console.log(error.failed); // true console.log(error.exitCode); // number or undefined console.log(error.signal); // 'SIGTERM', etc. or undefined console.log(error.timedOut); // boolean console.log(error.isCanceled); // boolean console.log(error.isTerminated); // boolean console.log(error.isMaxBuffer); // boolean // Error messages console.log(error.originalMessage); // Original error only console.log(error.shortMessage); // Error + command console.log(error.message); // Error + command + output // Output is still available console.log(error.stdout); console.log(error.stderr); } } ``` -------------------------------- ### Configure custom logging with Winston Source: https://github.com/sindresorhus/execa/blob/main/docs/debugging.md Uses the verbose option in Execa to route execution events to a Winston logger instance. ```javascript 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); }, }); ``` -------------------------------- ### CLI Spinner Source: https://github.com/sindresorhus/execa/blob/main/docs/bash.md Display a spinner while a command is running. Bash does not have a built-in spinner. Execa uses 'ora' for this functionality. ```bash # Bash does not provide with a builtin spinner ``` ```javascript // zx await spinner(() => $`node script.js`); ``` ```javascript // Execa import {oraPromise} from 'ora'; await oraPromise($`node script.js`); ``` -------------------------------- ### Redirect output to files Source: https://github.com/sindresorhus/execa/blob/main/readme.md Write command output directly to a file. ```js // Similar to: npm run build > output.txt await execa({stdout: {file: 'output.txt'}})`npm run build`; ``` -------------------------------- ### Correct usage of strict union options Source: https://github.com/sindresorhus/execa/blob/main/docs/typescript.md Demonstrates the correct approach using specific type imports or 'as const' assertions to satisfy strict union requirements. ```ts import {execa, type Options} from 'execa'; const spawnSubprocess = (serialization: Options['serialization']) => execa({serialization})`npm run build`; const options = {serialization: 'json'} as const; await execa(options)`npm run build`; ``` -------------------------------- ### Execute Subcommands and Capture Output with Execa Source: https://github.com/sindresorhus/execa/blob/main/docs/bash.md Capture the output of a subcommand executed with Execa and use it as input for another command. This is useful for piping command output. ```bash echo "$(npm run build)" ``` ```javascript // zx const result = await $`npm run build`; await $`echo ${result}`; ``` ```javascript // Execa const result = await $`npm run build`; await $`echo ${result}`; ``` -------------------------------- ### Enable full verbose mode Source: https://github.com/sindresorhus/execa/blob/main/docs/debugging.md Logs stdout, stderr, and IPC messages in addition to command metadata. ```js // build.js await execa({verbose: 'full'})`npm run build`; await execa({verbose: 'full'})`npm run test`; ``` -------------------------------- ### subprocess.pipe(file, arguments?, options?) Source: https://github.com/sindresorhus/execa/blob/main/docs/api.md Pipe the subprocess' stdout to a second Execa subprocess' stdin. ```APIDOC ## subprocess.pipe(file, arguments?, options?) ### Description Pipe the subprocess' stdout to a second Execa subprocess' stdin. Resolves with the second subprocess' result. ### Parameters - **file** (string | URL) - Required - The file to execute. - **arguments** (string[]) - Optional - Arguments for the command. - **options** (Options & PipeOptions) - Optional - Configuration options. ### Response - **Promise** - Resolves with the result of the piped subprocess. ``` -------------------------------- ### Template String Syntax with execa and $ Source: https://github.com/sindresorhus/execa/blob/main/docs/scripts.md Demonstrates using the template string syntax with both `execa` and the `$` operator. The `$` operator is not required when using template string syntax outside of script files. ```javascript import {execa, $} from 'execa'; const branch = await execa`git branch --show-current`; await $('dep', ['deploy', `--branch=${branch}`]); ``` -------------------------------- ### HTTP Requests Source: https://github.com/sindresorhus/execa/blob/main/docs/bash.md Make HTTP requests. Both zx and Execa leverage the global `fetch` API available in modern Node.js versions. ```bash # Bash curl https://github.com ``` ```javascript // zx await fetch('https://github.com'); ``` ```javascript // Execa await fetch('https://github.com'); ``` -------------------------------- ### Synchronous Execution with TypeScript Source: https://github.com/sindresorhus/execa/blob/main/docs/typescript.md Demonstrates using explicit types for synchronous process execution with Execa. ```ts import { execaSync as execaSync_, ExecaSyncError, type SyncResult, type SyncOptions, type StdinSyncOption, type StdoutStderrSyncOption, type TemplateExpression, type SyncVerboseObject, type ExecaSyncMethod, } from 'execa'; const execaSync: ExecaSyncMethod = execaSync_({preferLocal: true}); const options: SyncOptions = { stdin: 'inherit' satisfies StdinSyncOption, stdout: 'pipe' satisfies StdoutStderrSyncOption, stderr: 'pipe' satisfies StdoutStderrSyncOption, timeout: 1000, verbose(verboseLine: string, verboseObject: SyncVerboseObject) { return verboseObject.type === 'duration' ? verboseLine : undefined; }, }; const task: TemplateExpression = 'build'; try { const result: SyncResult = execaSync(options)`npm run ${task}`; console.log(result.stdout); } catch (error) { if (error instanceof ExecaSyncError) { console.error(error); } } ``` -------------------------------- ### options.stdout Configuration Source: https://github.com/sindresorhus/execa/blob/main/docs/api.md Configure the standard output for a subprocess. Supports various data types including strings, streams, file descriptors, and more. ```APIDOC ## options.stdout ### Description How to setup the subprocess' [standard output](https://en.wikipedia.org/wiki/Standard_streams#Standard_input_(stdin)). ### Type `string | number | stream.Writable | WritableStream | TransformStream | URL | {file: string} | GeneratorFunction | AsyncGeneratorFunction | {transform: GeneratorFunction | AsyncGeneratorFunction | Duplex | TransformStream}` (or a tuple of those types) ### Default `pipe` ### Available Values - `'pipe'` - `'overlapped'` - `'ignore'` - `'inherit'` - File descriptor integer - Node.js `Writable` stream - Web `WritableStream` - `{ file: 'path' }` object - File URL - Generator function - `Duplex` or web `TransformStream` ### Example This can be an [array of values](output.md#multiple-targets) such as `['inherit', 'pipe']` or `[fileUrl, 'pipe']`. More info on [available values](output.md), [streaming](streams.md) and [transforms](transform.md). ``` -------------------------------- ### Iterate over output lines Source: https://github.com/sindresorhus/execa/blob/main/readme.md Use async iteration to process output line by line as it arrives. ```js for await (const line of execa`npm run build`) { if (line.includes('WARN')) { console.warn(line); } } ``` -------------------------------- ### Encode binary output as a string Source: https://github.com/sindresorhus/execa/blob/main/docs/binary.md Use hex, base64, or base64url encoding to receive binary output as a formatted string. ```js const {stdout} = await execa({encoding: 'hex'})`zip -r - input.txt`; console.log(stdout); // Hexadecimal string ``` -------------------------------- ### Execute Command with Template String Syntax Source: https://github.com/sindresorhus/execa/blob/main/docs/execution.md Template string syntax offers a more concise way to execute commands, equivalent to the array syntax. ```javascript await execa`npm run build`; ``` -------------------------------- ### Configure stdout and stderr verbosity Source: https://github.com/sindresorhus/execa/blob/main/docs/output.md Apply verbose settings to output streams either globally or individually per stream. ```js // 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`; ``` -------------------------------- ### Execute a command synchronously Source: https://github.com/sindresorhus/execa/blob/main/docs/api.md Use `execaSync` for synchronous command execution. Note that this method is discouraged as it holds the CPU and lacks certain features. ```javascript execaSync("node", ["--version"]) ``` -------------------------------- ### Capture binary output Source: https://github.com/sindresorhus/execa/blob/main/docs/binary.md Set the encoding option to 'buffer' to receive output as a Uint8Array instead of a UTF8 string. ```js const {stdout} = await execa({encoding: 'buffer'})`zip -r - input.txt`; console.log(stdout.byteLength); ``` -------------------------------- ### Execute commands with user-defined input Source: https://github.com/sindresorhus/execa/blob/main/docs/escaping.md Pass variables directly into Execa commands using template strings or array arguments. ```js import {execa} from 'execa'; const file = 'npm'; const commandArguments = ['run', 'task with space']; await execa`${file} ${commandArguments}`; await execa(file, commandArguments); ```