### Install nano-spawn Source: https://github.com/sindresorhus/nano-spawn/blob/main/readme.md Command to install the package via npm. ```sh npm install nano-spawn ``` -------------------------------- ### Execute Commands on Windows with Nano Spawn Source: https://context7.com/sindresorhus/nano-spawn/llms.txt Shows how Nano Spawn handles Windows-specific binaries, batch files, and local npm packages without requiring shell mode. ```javascript import spawn from 'nano-spawn'; // These work on Windows without shell: true await spawn('npm', ['install']); // Runs npm.cmd await spawn('yarn', ['build']); // Runs yarn.cmd await spawn('npx', ['eslint', '--fix']); // Runs npx.cmd // .bat and .cmd files work automatically await spawn('build.cmd', ['--production']); await spawn('deploy.bat'); // Local npm binaries work with preferLocal await spawn('eslint', ['.'], { preferLocal: true }); await spawn('webpack', ['--config', 'prod.js'], { preferLocal: true }); // Windows-specific newlines (\r\n) are handled correctly const result = await spawn('cmd', ['/c', 'echo hello']); console.log(result.stdout); // 'hello' (newlines stripped) ``` -------------------------------- ### Configure spawn options Source: https://context7.com/sindresorhus/nano-spawn/llms.txt Advanced configuration for environment variables, local binary execution, stdin/stdout streams, and process cancellation. ```javascript import spawn from 'nano-spawn'; // Override environment variables (inherits process.env by default) const result1 = await spawn('printenv', ['NODE_ENV'], { env: { NODE_ENV: 'production' } }); // Execute locally installed npm binaries without npx const result2 = await spawn('eslint', ['--fix', '.'], { preferLocal: true // Adds node_modules/.bin to PATH }); // Pass string input to stdin const result3 = await spawn('cat', [], { stdin: { string: 'Hello from stdin!' } }); console.log(result3.stdout); // 'Hello from stdin!' // Use streams for input/output import { createReadStream, createWriteStream } from 'node:fs'; const inputStream = createReadStream('input.txt'); const outputStream = createWriteStream('output.txt'); await spawn('sort', [], { stdin: inputStream, stdout: outputStream }); // Inherit stdio for interactive commands await spawn('vim', ['file.txt'], { stdio: 'inherit' }); // Set timeout and cancellation const controller = new AbortController(); setTimeout(() => controller.abort(), 5000); try { await spawn('long-running-command', [], { signal: controller.signal, timeout: 10000 }); } catch (error) { if (error.isCanceled) { console.log('Command was canceled'); } } ``` -------------------------------- ### Windows Support Features Source: https://context7.com/sindresorhus/nano-spawn/llms.txt Overview of how Nano Spawn handles Windows-specific execution requirements automatically. ```APIDOC ## Windows Support ### Description Nano Spawn automatically manages Windows-specific execution quirks, allowing developers to run commands without manually enabling shell mode. ### Features - **Binary Resolution**: Automatically resolves and executes .cmd and .bat files. - **npm/npx Integration**: Correctly handles npm, yarn, and npx binaries. - **Local Binaries**: Supports `preferLocal: true` to execute binaries from node_modules/.bin. - **Newline Normalization**: Automatically handles Windows-style (\r\n) newlines in output. ``` -------------------------------- ### Run commands Source: https://github.com/sindresorhus/nano-spawn/blob/main/readme.md Execute a command and retrieve the output using the default export. ```js import spawn from 'nano-spawn'; const result = await spawn('echo', ['🦄']); console.log(result.output); //=> '🦄' ``` -------------------------------- ### spawn(file, arguments?, options?) Source: https://context7.com/sindresorhus/nano-spawn/llms.txt Executes a command using the specified file and arguments. Returns a Subprocess object that acts as both a Promise and an async iterable. ```APIDOC ## spawn(file, arguments?, options?) ### Description Executes a command using `file ...arguments`. Returns a `Subprocess` that resolves to a `Result` object and supports streaming output lines. ### Parameters #### Path Parameters - **file** (string) - Required - The command or file to execute. - **arguments** (string[]) - Optional - Array of arguments to pass to the command. #### Request Body (Options) - **cwd** (string) - Optional - Current working directory of the child process. - **timeout** (number) - Optional - Timeout in milliseconds. - **env** (object) - Optional - Environment key-value pairs. - **preferLocal** (boolean) - Optional - If true, adds node_modules/.bin to PATH. - **stdin** (object|stream) - Optional - Input for the process (string or stream). - **stdio** (string|array) - Optional - Child process stdio configuration. - **signal** (AbortSignal) - Optional - AbortSignal to cancel the process. ### Response #### Success Response (200) - **stdout** (string) - The standard output of the process. - **output** (string) - Combined stdout and stderr. - **command** (string) - The full command executed. - **durationMs** (number) - Execution time in milliseconds. ``` -------------------------------- ### Handle Subprocess Errors with Nano Spawn Source: https://context7.com/sindresorhus/nano-spawn/llms.txt Demonstrates catching and inspecting SubprocessError, handling signal terminations, command not found errors, and piped command failures. ```javascript import spawn, { SubprocessError } from 'nano-spawn'; // Handle subprocess errors try { await spawn('node', ['-e', 'process.exit(1)']); } catch (error) { if (error instanceof SubprocessError) { console.log(error.message); // 'Command failed with exit code 1: node -e ...' console.log(error.exitCode); // 1 console.log(error.stdout); // '' (captured output before failure) console.log(error.stderr); // '' console.log(error.command); // 'node -e process.exit(1)' console.log(error.durationMs); // 23.456 } } // Handle signal termination try { const controller = new AbortController(); setTimeout(() => controller.abort(), 100); await spawn('sleep', ['10'], { signal: controller.signal }); } catch (error) { console.log(error.signalName); // 'SIGTERM' console.log(error.isCanceled); // true console.log(error.exitCode); // undefined (terminated by signal) } // Handle command not found try { await spawn('nonexistent-command'); } catch (error) { console.log(error.message); // 'Command failed: nonexistent-command' console.log(error.cause); // Original ENOENT error } // Handle piped command failures try { await spawn('echo', ['test']) .pipe('grep', ['notfound']) .pipe('cat'); } catch (error) { // grep returns exit code 1 when no match console.log(error.exitCode); // 1 console.log(error.pipedFrom.stdout); // 'test' (echo succeeded) } ``` -------------------------------- ### Execute commands with spawn Source: https://context7.com/sindresorhus/nano-spawn/llms.txt Basic usage of the spawn function to run commands, handle arguments, and access result properties like stdout and duration. ```javascript import spawn from 'nano-spawn'; // Basic command execution const result = await spawn('echo', ['Hello, World!']); console.log(result.stdout); // 'Hello, World!' console.log(result.output); // 'Hello, World!' (combined stdout + stderr) console.log(result.command); // 'echo Hello, World!' console.log(result.durationMs); // 12.345 (execution time in ms) // Run git commands const gitResult = await spawn('git', ['status', '--short']); console.log(gitResult.stdout); // Execute Node.js scripts (inherits current Node version and flags) const nodeResult = await spawn('node', ['./script.js', '--flag']); console.log(nodeResult.stdout); // With options const customResult = await spawn('ls', ['-la'], { cwd: '/tmp', timeout: 5000, env: { MY_VAR: 'value' } }); ``` -------------------------------- ### Default Export: spawn() Source: https://github.com/sindresorhus/nano-spawn/blob/main/readme.md The main function to execute a command. It accepts the command file, arguments, and options, returning a Subprocess object. ```APIDOC ## spawn(file, arguments?, options?) ### Description Executes a command using `file ...arguments`. This has the same syntax as [`child_process.spawn()`](https://nodejs.org/api/child_process.html#child_processspawncommand-args-options). If `file` is `'node'`, the current Node.js version and [flags](https://nodejs.org/api/cli.html#options) are inherited. ### Method `spawn` ### Parameters #### Path Parameters - **file** (string) - Required - The command to execute. - **arguments** (string[]) - Optional - An array of string arguments for the command. #### Request Body - **options** (Options) - Optional - Configuration options for the spawn process. ### Options #### options.stdio, options.shell, options.timeout, options.signal, options.cwd, options.killSignal, options.serialization, options.detached, options.uid, options.gid, options.windowsVerbatimArguments, options.windowsHide, options.argv0 All [`child_process.spawn()`](https://nodejs.org/api/child_process.html#child_processspawncommand-args-options) options can be passed to `spawn()`. #### options.env - **env** (object) - Optional - Override specific [environment variables](https://en.wikipedia.org/wiki/Environment_variable). Other environment variables are inherited from the current process ([`process.env`](https://nodejs.org/api/process.html#processenv)). _Default_: `{}` #### options.preferLocal - **preferLocal** (boolean) - Optional - Allows executing binaries installed locally with `npm` (or `yarn`, etc.). _Default_: `false` ### Response _Returns_: [`Subprocess`](#subprocess) ### Request Example ```js import spawn from 'nano-spawn'; const result = await spawn('echo', ['🦄']); ``` ### Response Example ```js { // Subprocess object details would go here } ``` ``` -------------------------------- ### Execute a command with node:child_process Source: https://github.com/sindresorhus/nano-spawn/blob/main/readme.md Use promisify from 'node:util' to convert the execFile function from 'node:child_process' into a promise-based function for easier async/await usage. This is useful for executing external commands. ```javascript import {execFile} from 'node:child_process'; import {promisify} from 'node:util'; const pExecFile = promisify(execFile); const result = await pExecFile('npm', ['run', 'build']); ``` -------------------------------- ### Subprocess Options: stdin, stdout, stderr Source: https://github.com/sindresorhus/nano-spawn/blob/main/readme.md Configuration options for standard input, output, and error streams of a subprocess. ```APIDOC ## Options: stdin, stdout, stderr ### Description Configures the standard input, output, and error streams for a subprocess. ### Type `string | number | Stream | {string: string}` ### Supported Values - `'pipe'` (default): Captures output in `result.stdout`, `result.stderr`, and `result.output`. - `'inherit'`: Uses the parent process's stdio streams. Useful for terminal execution. - `'ignore'`: Discards stdio streams. - `Stream`: Redirects stdio to/from a Node.js stream (e.g., `fs.createReadStream`, `fs.createWriteStream`). - `{string: '...'}`: Provides a string as input to `stdin`. ``` -------------------------------- ### Subprocess Execution and Result Handling Source: https://github.com/sindresorhus/nano-spawn/blob/main/readme.md Details on how to execute a subprocess and handle its outcome. ```APIDOC ## Subprocess Execution ### Description Starts a subprocess using the `spawn()` function and handles its lifecycle. ### `await subprocess` #### Returns - `Result`: An object containing the subprocess's output and status upon successful completion. #### Throws - `SubprocessError`: An error object if the subprocess fails. ### `subprocess.stdout` #### Returns - `AsyncIterable`: An asynchronous iterable that yields lines from `stdout` as they become available. #### Throws - `SubprocessError`: If the subprocess fails during iteration. ### `subprocess.stderr` #### Returns - `AsyncIterable`: An asynchronous iterable that yields lines from `stderr` as they become available. #### Throws - `SubprocessError`: If the subprocess fails during iteration. ### `subprocess[Symbol.asyncIterator]()` #### Returns - `AsyncIterable`: An asynchronous iterable that yields lines from both `stdout` and `stderr`. #### Throws - `SubprocessError`: If the subprocess fails during iteration. ### `subprocess.pipe(file, arguments?, options?)` #### Parameters - `file` (string): The command to execute for the next subprocess. - `arguments` (string[]): Arguments for the next subprocess. - `options` (Options): Configuration options for the next subprocess. #### Returns - `Subprocess`: A new subprocess representing the piped command chain. ### `await subprocess.nodeChildProcess` #### Type - `ChildProcess`: The underlying Node.js child process instance, allowing access to methods like `.kill()` and `.send()`. ``` -------------------------------- ### Iterate over output lines Source: https://github.com/sindresorhus/nano-spawn/blob/main/readme.md Use an asynchronous iterator to process output line by line. ```js for await (const line of spawn('ls', ['--oneline'])) { console.log(line); } //=> index.d.ts //=> index.js //=> … ``` -------------------------------- ### Subprocess API Source: https://github.com/sindresorhus/nano-spawn/blob/main/readme.md Details about the Subprocess object returned by the spawn function, including its methods and properties. ```APIDOC ## Subprocess Object ### Description The `Subprocess` object represents an ongoing or completed child process execution. ### Methods #### iterate over output lines (`[Symbol.asyncIterator]`) Allows iterating over the output lines of the subprocess asynchronously. ```js for await (const line of spawn('ls', ['--oneline'])) { console.log(line); } ``` #### pipe(file, arguments?, options?) Pipes the output of the current subprocess to another command. ```js const result = await spawn('npm', ['run', 'build']) .pipe('sort') .pipe('head', ['-n', '2']); ``` ### Properties - **output** (string) - The combined stdout and stderr output of the subprocess. - **stdout** (string) - The stdout of the subprocess. Unnecessary newlines are stripped. - **stderr** (string) - The stderr of the subprocess. - **durationMs** (number) - The duration of the subprocess execution in milliseconds. - **exitCode** (number | null) - The exit code of the subprocess. `null` if the process was terminated by a signal. ### Errors - **SubprocessError** - Custom error type for subprocess failures, providing better error messages. ``` -------------------------------- ### Pipe commands Source: https://github.com/sindresorhus/nano-spawn/blob/main/readme.md Chain multiple subprocesses together using the pipe method. ```js const result = await spawn('npm', ['run', 'build']) .pipe('sort') .pipe('head', ['-n', '2']); ``` -------------------------------- ### Subprocess Object Source: https://context7.com/sindresorhus/nano-spawn/llms.txt The object returned by spawn() provides access to the underlying Node.js ChildProcess and lifecycle management. ```APIDOC ## Subprocess Object ### Description Returned by `spawn()`, this object is both a Promise and an async iterable. It allows access to the underlying Node.js `ChildProcess` instance. ### Properties - **nodeChildProcess** (ChildProcess) - The underlying Node.js child process instance. ### Methods - **await subprocess** - Resolves to the `Result` object. - **childProcess.kill(signal)** - Terminates the subprocess. - **childProcess.send(message)** - Sends an IPC message (requires stdio: 'ipc'). ``` -------------------------------- ### Interact with Subprocess objects Source: https://context7.com/sindresorhus/nano-spawn/llms.txt Accessing the underlying Node.js ChildProcess, managing process lifecycle, and handling IPC communication. ```javascript import spawn from 'nano-spawn'; // Await the subprocess to get the full result const subprocess = spawn('echo', ['test']); const result = await subprocess; console.log(result.stdout); // 'test' // Access the underlying Node.js ChildProcess const proc = spawn('sleep', ['10']); const childProcess = await proc.nodeChildProcess; console.log(childProcess.pid); // Process ID // Kill the subprocess childProcess.kill('SIGTERM'); // Send IPC messages (requires stdio: ['pipe', 'pipe', 'pipe', 'ipc']) const ipcProc = spawn('node', ['worker.js'], { stdio: ['pipe', 'pipe', 'pipe', 'ipc'] }); const child = await ipcProc.nodeChildProcess; child.send({ type: 'start', data: [1, 2, 3] }); ``` -------------------------------- ### Iterate over stdout lines Source: https://context7.com/sindresorhus/nano-spawn/llms.txt Access the stdout property to iterate exclusively over standard output lines. ```javascript import spawn from 'nano-spawn'; // Iterate only over stdout for await (const line of spawn('ls', ['-la']).stdout) { console.log('File:', line); } // Parse JSON lines from stdout const subprocess = spawn('node', ['-e', ` console.log(JSON.stringify({ id: 1, name: 'Alice' })); console.log(JSON.stringify({ id: 2, name: 'Bob' })); `]); const users = []; for await (const line of subprocess.stdout) { users.push(JSON.parse(line)); } console.log(users); // [{ id: 1, name: 'Alice' }, { id: 2, name: 'Bob' }] // Stream log processing for await (const line of spawn('tail', ['-f', '/var/log/app.log']).stdout) { const parsed = parseLogLine(line); if (parsed.level === 'error') { await alertAdmin(parsed); } } ``` -------------------------------- ### Iterating Over Subprocess Output Source: https://context7.com/sindresorhus/nano-spawn/llms.txt Iterate over interleaved stdout and stderr lines as they become available. The iteration automatically waits for the subprocess to complete and throws if it fails. ```APIDOC ## Iterating Over Subprocess Output ### Description Iterate over interleaved stdout and stderr lines as they become available. The iteration automatically waits for the subprocess to complete and throws if it fails, so explicit `await subprocess` is not needed. ### Method `subprocess[Symbol.asyncIterator]()` ### Endpoint N/A (Method on subprocess object) ### Parameters None ### Request Example ```javascript import spawn from 'nano-spawn'; // Iterate over all output lines (stdout + stderr interleaved) for await (const line of spawn('npm', ['install'])) { console.log(line); } // Process output with early termination const lines = []; for await (const line of spawn('find', ['.', '-name', '*.js'])) { lines.push(line); if (lines.length >= 10) { break; // Still waits for subprocess to complete } } console.log(`First 10 JS files: ${lines.join(', ')}`); // Use with async generators async function* filterErrors(subprocess) { for await (const line of subprocess) { if (line.includes('ERROR')) { yield line; } } } for await (const errorLine of filterErrors(spawn('npm', ['run', 'build']))) { console.error('Build error:', errorLine); } ``` ### Response Async iterable yielding lines of output from the subprocess. ``` -------------------------------- ### Pipe subprocesses Source: https://context7.com/sindresorhus/nano-spawn/llms.txt Chain commands using the pipe method to pass stdout from one process to the stdin of another. ```javascript import spawn from 'nano-spawn'; // Simple pipe: equivalent to `cat file.txt | grep "pattern"` const result = await spawn('cat', ['file.txt']) .pipe('grep', ['pattern']); console.log(result.stdout); // Multiple pipes: equivalent to `ps aux | grep node | wc -l` const result2 = await spawn('ps', ['aux']) .pipe('grep', ['node']) .pipe('wc', ['-l']); console.log(`Node processes: ${result2.stdout.trim()}`); // Access intermediate results via pipedFrom const result3 = await spawn('echo', ['3\n1\n2']) .pipe('sort') .pipe('head', ['-n', '1']); console.log(result3.stdout); // '1' console.log(result3.pipedFrom.stdout); // '1\n2\n3' (output from sort) console.log(result3.pipedFrom.pipedFrom.stdout); // '3\n1\n2' (output from echo) // Build pipeline with complex commands const searchResult = await spawn('find', ['.', '-name', '*.js']) .pipe('xargs', ['grep', '-l', 'TODO']) .pipe('sort') .pipe('uniq'); console.log('Files with TODOs:', searchResult.stdout); // Pipe with options on each command const result4 = await spawn('npm', ['run', 'build'], { cwd: './frontend' }) .pipe('tee', ['build.log']) .pipe('grep', ['-E', '^(ERROR|WARN)']); ``` -------------------------------- ### Subprocess Result Object Source: https://github.com/sindresorhus/nano-spawn/blob/main/readme.md Details the properties returned upon a successful subprocess execution. ```APIDOC ## Subprocess Result Object ### Description The result object returned after a successful subprocess execution. ### Properties - **output** (string) - Interleaved standard output and standard error. - **command** (string) - The file and arguments that were run. - **durationMs** (number) - Duration of the subprocess in milliseconds. - **pipedFrom** (Result | SubprocessError | undefined) - The result or error of a previous subprocess if piped. ``` -------------------------------- ### Accessing Subprocess STDERR Source: https://context7.com/sindresorhus/nano-spawn/llms.txt Provides an async iterable that yields only stderr lines, useful for monitoring error output separately. ```APIDOC ## Accessing Subprocess STDERR ### Description Async iterable that yields only stderr lines. Useful for monitoring error output separately. ### Method `subprocess.stderr` ### Endpoint N/A (Property on subprocess object) ### Parameters None ### Request Example ```javascript import spawn from 'nano-spawn'; // Capture only error output const errors = []; for await (const line of spawn('npm', ['install']).stderr) { if (line.includes('WARN')) { errors.push(line); } } console.log('Warnings:', errors); // Monitor stderr while ignoring stdout const proc = spawn('webpack', ['--watch']); for await (const line of proc.stderr) { console.error('Webpack error:', line); } ``` ### Response Async iterable yielding only stderr lines from the subprocess. ``` -------------------------------- ### Accessing Subprocess STDOUT Source: https://context7.com/sindresorhus/nano-spawn/llms.txt Provides an async iterable that yields only stdout lines, useful for processing stdout separately from stderr. ```APIDOC ## Accessing Subprocess STDOUT ### Description Async iterable that yields only stdout lines. Useful when you need to process stdout separately from stderr. ### Method `subprocess.stdout` ### Endpoint N/A (Property on subprocess object) ### Parameters None ### Request Example ```javascript import spawn from 'nano-spawn'; // Iterate only over stdout for await (const line of spawn('ls', ['-la']).stdout) { console.log('File:', line); } // Parse JSON lines from stdout const subprocess = spawn('node', ['-e', ` console.log(JSON.stringify({ id: 1, name: 'Alice' })); console.log(JSON.stringify({ id: 2, name: 'Bob' })); `]); const users = []; for await (const line of subprocess.stdout) { users.push(JSON.parse(line)); } console.log(users); // [{ id: 1, name: 'Alice' }, { id: 2, name: 'Bob' }] ``` ### Response Async iterable yielding only stdout lines from the subprocess. ``` -------------------------------- ### SubprocessError Class Source: https://context7.com/sindresorhus/nano-spawn/llms.txt Details on the SubprocessError class thrown when a subprocess fails, including properties for exit codes, signals, and cancellation status. ```APIDOC ## SubprocessError ### Description An error class that extends the native Error object, thrown when a spawned subprocess fails. It provides detailed diagnostic information about the failure. ### Properties - **exitCode** (number) - The exit code of the process, if available. - **signalName** (string) - The signal name that terminated the process, if applicable. - **isCanceled** (boolean) - Indicates if the process was aborted via an AbortSignal. - **stdout** (string) - Captured standard output before the failure. - **stderr** (string) - Captured standard error output. - **command** (string) - The command string that was executed. - **durationMs** (number) - The execution time in milliseconds. - **cause** (Error) - The original error object (e.g., ENOENT for command not found). - **pipedFrom** (object) - Reference to the previous process in a pipe chain. ``` -------------------------------- ### Piping Subprocesses Source: https://context7.com/sindresorhus/nano-spawn/llms.txt Pipes the stdout of one subprocess to the stdin of another, similar to the `|` operator in shells. Returns a new `Subprocess` that resolves with the final result. ```APIDOC ## Piping Subprocesses ### Description Pipes the stdout of one subprocess to the stdin of another, similar to the `|` operator in shells. Returns a new `Subprocess` that resolves with the final result and includes `pipedFrom` containing results from earlier commands in the pipeline. ### Method `subprocess.pipe(file, arguments?, options?) ### Endpoint N/A (Method on subprocess object) ### Parameters - **file** (string) - The command to pipe to. - **arguments** (string[]) - Optional arguments for the piped command. - **options** (object) - Optional options for the piped command. ### Request Example ```javascript import spawn from 'nano-spawn'; // Simple pipe: equivalent to `cat file.txt | grep "pattern"` const result = await spawn('cat', ['file.txt']) .pipe('grep', ['pattern']); console.log(result.stdout); // Multiple pipes: equivalent to `ps aux | grep node | wc -l` const result2 = await spawn('ps', ['aux']) .pipe('grep', ['node']) .pipe('wc', ['-l']); console.log(`Node processes: ${result2.stdout.trim()}`); // Access intermediate results via pipedFrom const result3 = await spawn('echo', ['3\n1\n2']) .pipe('sort') .pipe('head', ['-n', '1']); console.log(result3.stdout); // '1' console.log(result3.pipedFrom.stdout); // '1\n2\n3' (output from sort) console.log(result3.pipedFrom.pipedFrom.stdout); // '3\n1\n2' (output from echo) // Build pipeline with complex commands const searchResult = await spawn('find', ['.', '-name', '*.js']) .pipe('xargs', ['grep', '-l', 'TODO']) .pipe('sort') .pipe('uniq'); console.log('Files with TODOs:', searchResult.stdout); // Pipe with options on each command const result4 = await spawn('npm', ['run', 'build'], { cwd: './frontend' }) .pipe('tee', ['build.log']) .pipe('grep', ['-E', '^(ERROR|WARN)']); ``` ### Response A new `Subprocess` object representing the piped command. It resolves with the final result and includes `pipedFrom` properties for intermediate results. ``` -------------------------------- ### SubprocessError Object Source: https://github.com/sindresorhus/nano-spawn/blob/main/readme.md Details the properties of the error object thrown when a subprocess fails. ```APIDOC ## SubprocessError Object ### Description Thrown when a subprocess fails due to non-zero exit codes, signals, or execution errors. ### Properties - **exitCode** (number | undefined) - The numeric exit code of the subprocess. - **signalName** (string | undefined) - The name of the signal that terminated the subprocess. - **isCanceled** (boolean) - Whether the subprocess was canceled via the signal option. ``` -------------------------------- ### Iterate over stderr lines Source: https://context7.com/sindresorhus/nano-spawn/llms.txt Access the stderr property to monitor error output separately from standard output. ```javascript import spawn from 'nano-spawn'; // Capture only error output const errors = []; for await (const line of spawn('npm', ['install']).stderr) { if (line.includes('WARN')) { errors.push(line); } } console.log('Warnings:', errors); // Monitor stderr while ignoring stdout const proc = spawn('webpack', ['--watch']); for await (const line of proc.stderr) { console.error('Webpack error:', line); } ``` -------------------------------- ### Iterate over subprocess output with Symbol.asyncIterator Source: https://context7.com/sindresorhus/nano-spawn/llms.txt Use the async iterator to process interleaved stdout and stderr lines. The iteration automatically waits for the subprocess to complete. ```javascript import spawn from 'nano-spawn'; // Iterate over all output lines (stdout + stderr interleaved) for await (const line of spawn('npm', ['install'])) { console.log(line); } // Output appears in real-time as the command runs // Process output with early termination const lines = []; for await (const line of spawn('find', ['.', '-name', '*.js'])) { lines.push(line); if (lines.length >= 10) { break; // Still waits for subprocess to complete } } console.log(`First 10 JS files: ${lines.join(', ')}`); // Use with async generators async function* filterErrors(subprocess) { for await (const line of subprocess) { if (line.includes('ERROR')) { yield line; } } } for await (const errorLine of filterErrors(spawn('npm', ['run', 'build']))) { console.error('Build error:', errorLine); } ``` -------------------------------- ### Result Object Structure Source: https://github.com/sindresorhus/nano-spawn/blob/main/readme.md Defines the structure of the Result object returned upon successful subprocess execution. ```APIDOC ## Result Object ### Description An object returned when a subprocess completes successfully. ### Properties #### `result.stdout` - **Type**: `string` - **Description**: The content of the standard output. Trailing newlines are automatically stripped. This property is an empty string if `stdout` was not set to `'pipe'` or if it's being iterated via `subprocess.stdout` or `subprocess[Symbol.asyncIterator]`. #### `result.stderr` - **Type**: `string` - **Description**: The content of the standard error. Similar behavior to `result.stdout` regarding trailing newlines and availability when iterating. ``` -------------------------------- ### Access subprocess result Source: https://context7.com/sindresorhus/nano-spawn/llms.txt Retrieve the result object containing stdout, stderr, and metadata after a subprocess completes. ```javascript import spawn from 'nano-spawn'; const result = await spawn('node', ['-e', ` console.log('stdout message'); console.error('stderr message'); `]); console.log(result.stdout); // 'stdout message' console.log(result.stderr); // 'stderr message' console.log(result.output); // 'stdout message\nstderr message' (interleaved order) console.log(result.command); // 'node -e ...' console.log(result.durationMs); // 45.678 // Trailing newlines are automatically stripped const echoResult = await spawn('echo', ['hello']); console.log(echoResult.stdout); // 'hello' (not 'hello\n') // Access piped command results const pipeResult = await spawn('echo', ['hello']).pipe('cat'); console.log(pipeResult.pipedFrom.stdout); // 'hello' console.log(pipeResult.pipedFrom.command); // 'echo hello' ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.