### Instantiate and Spawn ExecProcess Source: https://github.com/tinylibs/tinyexec/blob/main/_autodocs/api-reference/execprocess-class.md Example of creating an ExecProcess instance and manually spawning it. The process is then awaited to get the result. ```typescript import {ExecProcess} from 'tinyexec'; const proc = new ExecProcess('echo', ['test']); proc.spawn(); const result = await proc; console.log(result.stdout); ``` -------------------------------- ### Install tinyexec Source: https://github.com/tinylibs/tinyexec/blob/main/README.md Install the tinyexec package using npm. ```sh $ npm i -S tinyexec ``` -------------------------------- ### PipeOptions Usage Example Source: https://github.com/tinylibs/tinyexec/blob/main/_autodocs/types.md Shows an example of using PipeOptions with the .pipe() method, including a timeout configuration. ```typescript const result = await x('find', ['.', '-type', 'f']) .pipe('grep', ['pattern'], {timeout: 5000}); ``` -------------------------------- ### Example Usage of xSync Source: https://github.com/tinylibs/tinyexec/blob/main/_autodocs/types.md Demonstrates how to use the xSync function with custom timeout and error handling options. ```typescript const result = xSync('ls', ['-la'], { timeout: 2000, throwOnError: true }); ``` -------------------------------- ### Direct Instantiation and Spawning Source: https://github.com/tinylibs/tinyexec/blob/main/_autodocs/api-reference/execprocess-class.md Demonstrates how to create an ExecProcess instance, manually spawn it, and then await its completion to get the result. ```APIDOC ## Direct Instantiation ### Description Instantiate an `ExecProcess` object with a command and its arguments. You must manually call `spawn()` to start the process, and then you can `await` the instance to get the execution `Result`. ### Usage ```typescript import {ExecProcess} from 'tinyexec'; // Create instance const proc = new ExecProcess('node', ['-e', 'console.log("hi")']); // Must manually spawn proc.spawn(); // Then use like normal const result = await proc; console.log(result.stdout); ``` ### Related - [x function](./exec-function.md) - [Result type](./types.md#result) ``` -------------------------------- ### ExecProcess Constructor Source: https://github.com/tinylibs/tinyexec/blob/main/_autodocs/api-reference/execprocess-class.md Initializes a new ExecProcess instance. The process is not spawned immediately; use spawn() to start it. ```APIDOC ## Constructor Initializes a new `ExecProcess` instance. ### Signature ```typescript new ExecProcess(command: string, args?: readonly string[], options?: Partial): ExecProcess ``` ### Parameters - **command** (string) - Required - The command to execute. - **args** (readonly string[]) - Optional - Array of command arguments. Defaults to `[]`. - **options** (Partial) - Optional - Configuration options for execution. Defaults to `{}`. ``` -------------------------------- ### Using Locally Installed Binaries Source: https://github.com/tinylibs/tinyexec/blob/main/_autodocs/api-reference/exec-function.md Execute commands that are installed locally within the project's `node_modules/.bin` directory. By default, `tinyexec` adds this directory to the PATH, allowing direct execution of local binaries like `eslint`. ```typescript import {x} from 'tinyexec'; // Assuming eslint is installed locally const result = await x('eslint', ['.']); ``` -------------------------------- ### Named Imports Example Source: https://github.com/tinylibs/tinyexec/blob/main/_autodocs/api-reference/exports-reference.md Demonstrates how to perform named imports for functions and error types from the 'tinyexec' library. ```typescript import {x, xSync, NonZeroExitError} from 'tinyexec'; const result = await x('ls', ['-l']); ``` -------------------------------- ### Options Usage Example Source: https://github.com/tinylibs/tinyexec/blob/main/_autodocs/types.md Illustrates how to configure and use the Options interface with the asynchronous x() function, setting timeout, throwOnError, signal, and stdin. ```typescript const options: Partial = { timeout: 5000, throwOnError: true, signal: controller.signal, stdin: 'input data' }; const result = await x('node', ['script.js'], options); ``` -------------------------------- ### Execute locally installed node binaries Source: https://github.com/tinylibs/tinyexec/blob/main/README.md Execute binaries installed in the project's node_modules directory by default. ```ts await x('eslint', ['.']); ``` -------------------------------- ### Selective Imports Example Source: https://github.com/tinylibs/tinyexec/blob/main/_autodocs/api-reference/exports-reference.md Shows how to import specific types for type-checking purposes, such as Result, Output, and Options. ```typescript // Type-only import import type {Result, Output, Options} from 'tinyexec'; async function myFunction(opts: Partial): Promise { const result = await x('echo', ['hi'], opts); return result; } ``` -------------------------------- ### Aliased Imports Example Source: https://github.com/tinylibs/tinyexec/blob/main/_autodocs/api-reference/exports-reference.md Illustrates how to import and alias functions and types from 'tinyexec' for alternative naming conventions. ```typescript import {x as execute, ExecProcess as Process} from 'tinyexec'; const result = await execute('node', ['script.js']); ``` -------------------------------- ### SyncResult Usage Example Source: https://github.com/tinylibs/tinyexec/blob/main/_autodocs/types.md Demonstrates how to use the SyncResult type with the xSync function and iterate over its output. ```typescript const result: SyncResult = xSync('echo', ['hello']); console.log(result.stdout); // "hello\n" console.log(result.exitCode); // 0 for (const line of result) { console.log(line); } ``` -------------------------------- ### API Reference Functions Source: https://github.com/tinylibs/tinyexec/blob/main/_autodocs/DOCUMENTATION_SUMMARY.txt Detailed documentation for the `x()` and `exec()` functions, including their signatures, parameters, return values, error conditions, and usage examples. ```APIDOC ## x() and exec() ### Description Executes a command asynchronously. Provides detailed information about the process execution, including stdout, stderr, and exit code. ### Method `x(command, options)` or `exec(command, options)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **command** (string | string[]) - Required - The command to execute. - **options** (Options) - Optional - Configuration options for the execution. ``` -------------------------------- ### Accessing Local Node Modules Source: https://github.com/tinylibs/tinyexec/blob/main/_autodocs/quick-reference.md Demonstrates how to execute locally installed Node modules using the `x` function. By default, it looks in `./node_modules/.bin`. Set `nodePath: false` to use system-wide binaries. ```typescript await x('eslint', ['.']); ``` ```typescript await x('eslint', ['.'], {nodePath: false}); ``` -------------------------------- ### Example Usage of Process Kill Signals Source: https://github.com/tinylibs/tinyexec/blob/main/_autodocs/types.md Shows how to terminate a spawned process gracefully with SIGTERM or forcefully with SIGKILL. ```typescript const proc = x('node', ['./long.js']); proc.kill('SIGKILL'); // Force kill // or proc.kill('SIGTERM'); // Graceful termination ``` -------------------------------- ### Example Usage of Output Interface Source: https://github.com/tinylibs/tinyexec/blob/main/_autodocs/types.md Demonstrates how to await a Result and access its stdout, stderr, and exitCode properties. Output is not trimmed and preserves trailing newlines. ```typescript const result: Output = await x('echo', ['hello']); console.log(result.stdout); // "hello\n" console.log(result.stderr); // "" console.log(result.exitCode); // 0 ``` -------------------------------- ### ExecProcess spawn() Method Signature Source: https://github.com/tinylibs/tinyexec/blob/main/_autodocs/api-reference/execprocess-class.md The signature for the spawn() method, which starts the child process. This is called automatically by the x() function. ```typescript spawn(): void ``` -------------------------------- ### Execute Command and Get Result Source: https://github.com/tinylibs/tinyexec/blob/main/_autodocs/integration-patterns.md Use for simple, one-off command execution. Imports the 'x' function from 'tinyexec'. ```typescript import {x} from 'tinyexec'; async function runCommand() { const result = await x('npm', ['--version']); console.log(result.stdout); console.log('Exit code:', result.exitCode); } ``` -------------------------------- ### API Reference Synchronous Functions Source: https://github.com/tinylibs/tinyexec/blob/main/_autodocs/DOCUMENTATION_SUMMARY.txt Detailed documentation for the `xSync()` and `execSync()` functions, including their signatures, parameters, return values, error conditions, and usage examples. ```APIDOC ## xSync() and execSync() ### Description Executes a command synchronously. Returns the result of the process execution, including stdout, stderr, and exit code, after the process has completed. ### Method `xSync(command, options)` or `execSync(command, options)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **command** (string | string[]) - Required - The command to execute. - **options** (SyncOptions) - Optional - Configuration options for the synchronous execution. ``` -------------------------------- ### Chain Multiple Commands with pipe() Source: https://github.com/tinylibs/tinyexec/blob/main/_autodocs/api-reference/execprocess-class.md Example of using the pipe() method to chain multiple commands, passing the output of one to the next. The final result is awaited. ```typescript const result = await x('ls', ['-la']) .pipe('grep', ['.js']) .pipe('wc', ['-l']); console.log('Count of .js files:', result.stdout); ``` -------------------------------- ### Run Local NPM Binaries Source: https://github.com/tinylibs/tinyexec/blob/main/_autodocs/integration-patterns.md Access locally installed npm packages, such as linters or formatters, using the x function. By default, node_modules/.bin is added to the PATH. ```typescript import {x} from 'tinyexec'; async function runEslint() { // By default, nodePath: true adds node_modules/.bin to PATH const result = await x('eslint', ['.'], { throwOnError: false // eslint exit 0 = success, 1 = errors }); if (result.exitCode === 0) { console.log('Lint passed'); } else { console.log('Lint errors found'); console.log(result.stdout); } } ``` -------------------------------- ### Pipe Multiple Commands with x Function Source: https://github.com/tinylibs/tinyexec/blob/main/_autodocs/api-reference/execprocess-class.md Shows how to chain multiple commands using the pipe method, starting with the x function. The final result contains the output of the last command in the chain. ```typescript import {x} from 'tinyexec'; const result = await x('find', ['.', '-type', 'f']) .pipe('grep', ['\.ts$']) .pipe('wc', ['-l']); console.log('TypeScript files:', result.stdout); ``` -------------------------------- ### Stream ExecProcess Output Line-by-Line Source: https://github.com/tinylibs/tinyexec/blob/main/_autodocs/api-reference/execprocess-class.md Example of iterating over an ExecProcess asynchronously to receive its output line by line. This is useful for large outputs or real-time processing. ```typescript const proc = x('find', ['.', '-name', '*.js']); for await (const line of proc) { console.log('File:', line); } ``` -------------------------------- ### Handle ExecProcess Result with then() Source: https://github.com/tinylibs/tinyexec/blob/main/_autodocs/api-reference/execprocess-class.md Example of using the then() method to handle both successful and rejected outcomes of an ExecProcess. This is an alternative to await. ```typescript const proc = x('echo', ['hello']); proc.then( (output) => console.log('Success:', output.stdout), (error) => console.error('Failed:', error) ); ``` -------------------------------- ### Kill ExecProcess After Timeout Source: https://github.com/tinylibs/tinyexec/blob/main/_autodocs/api-reference/execprocess-class.md Example demonstrating how to kill a process after a specified delay using the kill() method. The process is then awaited. ```typescript const proc = x('node', ['./long-running.js']); setTimeout(() => { const killed = proc.kill(); console.log('Killed:', killed); }, 5000); await proc; ``` -------------------------------- ### Handle Command Timeout with Fallback Source: https://github.com/tinylibs/tinyexec/blob/main/_autodocs/errors.md Implement a timeout for command execution and provide a fallback mechanism if the timeout is exceeded. This example returns null on timeout. ```typescript async function executeWithTimeout(cmd, args, timeoutMs = 5000) { const proc = x(cmd, args, {timeout: timeoutMs}); const result = await proc; if (proc.killed && !proc.aborted) { console.log('Timeout exceeded'); return null; } return result; } ``` -------------------------------- ### Pipe Commands Together Source: https://github.com/tinylibs/tinyexec/blob/main/_autodocs/README.md Chain multiple commands using the `.pipe()` method to send the output of one command as the input to the next. This example pipes 'ls' output to 'grep' and then to 'wc'. ```typescript const result = await x('ls', ['-la']) .pipe('grep', ['.js']) .pipe('wc', ['-l']); ``` -------------------------------- ### Setting Environment Variables for Child Process Source: https://github.com/tinylibs/tinyexec/blob/main/_autodocs/configuration.md Demonstrates how to set environment variables for a child process using the `env` property within `nodeOptions`. This example sets a custom environment variable `MY_VAR` for the `printenv` command. ```typescript const result = await x('printenv', ['MY_VAR'], { nodeOptions: { env: { ...process.env, MY_VAR: 'my-value' } } }); console.log(result.stdout); // "my-value\n" ``` -------------------------------- ### Normalize Command for Cross-Platform Spawn Source: https://github.com/tinylibs/tinyexec/blob/main/_autodocs/api-reference/normalize-spawn-command.md Get the normalized command and arguments suitable for `child_process.spawn` on the current platform. This function handles platform-specific escaping and shebang interpretation. ```typescript import {normalizeSpawnCommand} from 'tinyexec'; import {spawn} from 'child_process'; // Get normalized command for the current platform const normalized = normalizeSpawnCommand('npm', ['run', 'build']); // Use with spawn directly const proc = spawn(normalized.command, normalized.args, normalized.options); proc.stdout?.on('data', (data) => { console.log(data.toString()); }); ``` -------------------------------- ### Streaming Output Line-by-Line Source: https://github.com/tinylibs/tinyexec/blob/main/_autodocs/api-reference/exec-function.md Execute a command and process its output line by line as it becomes available. This is efficient for commands that produce large amounts of output. The command execution is awaited after iterating through the lines to get the final result. ```typescript import {x} from 'tinyexec'; const proc = x('ls', ['-l']); for await (const line of proc) { console.log('Line:', line); } const result = await proc; console.log('Exit code:', result.exitCode); ``` -------------------------------- ### Execute Batch Operations Sequentially in TypeScript Source: https://github.com/tinylibs/tinyexec/blob/main/_autodocs/integration-patterns.md Run multiple commands in a specific order, ensuring each completes successfully before the next starts. Use 'throwOnError: true' for each command to halt execution if any step fails. ```typescript import {x} from 'tinyexec'; // Sequential async function sequentialBuild() { await x('npm', ['run', 'lint'], {throwOnError: true}); await x('npm', ['run', 'build'], {throwOnError: true}); await x('npm', ['test'], {throwOnError: true}); } ``` -------------------------------- ### Get Exit Code Source: https://github.com/tinylibs/tinyexec/blob/main/README.md Access the `exitCode` property to get the exit code of the process after it has completed execution. ```typescript const proc = x('ls'); proc.exitCode; // number (e.g. 1) ``` -------------------------------- ### exitCode Source: https://github.com/tinylibs/tinyexec/blob/main/_autodocs/api-reference/execprocess-class.md Gets the exit code of the child process. Returns undefined if the process has not yet exited. ```APIDOC ## exitCode ### Description Gets the exit code of the child process. ### Type `number | undefined` ### Value The exit code (typically 0 for success), or undefined if the process hasn't exited yet. ### Example ```typescript const proc = x('echo', ['test']); // Before awaiting: console.log('Exit code:', proc.exitCode); // undefined const result = await proc; // After awaiting: console.log('Exit code:', proc.exitCode); // 0 console.log('Exit code:', result.exitCode); // 0 ``` ``` -------------------------------- ### Get Process ID (PID) Source: https://github.com/tinylibs/tinyexec/blob/main/README.md Retrieve the process ID of the executed command using the `pid` property. ```typescript const proc = x('ls'); proc.pid; // number ``` -------------------------------- ### Piping Multiple Commands Source: https://github.com/tinylibs/tinyexec/blob/main/_autodocs/api-reference/execprocess-class.md Illustrates how to chain commands using the `pipe` method on an ExecProcess instance created by the `x` function. ```APIDOC ## Piping Multiple Commands ### Description Chain commands together using the `.pipe()` method. The output of one command becomes the input of the next. This example finds all files, filters for TypeScript files, and then counts them. ### Usage ```typescript import {x} from 'tinyexec'; const result = await x('find', ['.', '-type', 'f']) .pipe('grep', ['\.ts$']) .pipe('wc', ['-l']); console.log('TypeScript files:', result.stdout); ``` ### Related - [x function](./exec-function.md) ``` -------------------------------- ### Execute Command with Basic Options Source: https://github.com/tinylibs/tinyexec/blob/main/_autodocs/configuration.md Run a command with timeout, error throwing, and nodePath options. Ensures local binaries are used. ```typescript import {x} from 'tinyexec'; const result = await x('eslint', ['.'], { timeout: 30000, // 30 seconds throwOnError: true, nodePath: true // Use local eslint from node_modules/.bin }); ``` -------------------------------- ### TinyExec File Manifest Source: https://github.com/tinylibs/tinyexec/blob/main/_autodocs/INDEX.md Lists all files analyzed for the TinyExec project, including the main documentation index, README, quick reference, API-related files, and utility modules. ```text output/ ├── INDEX.md (this file) ├── README.md (project overview) ├── quick-reference.md (quick lookup) ├── types.md (type definitions) ├── configuration.md (options reference) ├── errors.md (error catalog) ├── integration-patterns.md (usage patterns) ├── module-architecture.md (internals) └── api-reference/ ├── exec-function.md (x/exec function) ├── xsync-function.md (xSync/execSync function) ├── execprocess-class.md (ExecProcess class) ├── non-zero-exit-error.md (error class) ├── normalize-spawn-command.md (normalization) └── exports-reference.md (all exports) ``` -------------------------------- ### Execute command with options Source: https://github.com/tinylibs/tinyexec/blob/main/README.md Pass options to control process spawning, such as setting a timeout. ```ts await x('ls', [], { timeout: 1000 }); ``` -------------------------------- ### Basic Synchronous Execution with xSync Source: https://github.com/tinylibs/tinyexec/blob/main/_autodocs/api-reference/xsync-function.md Execute a command synchronously and log its standard output and exit code. Ensure 'tinyexec' is imported. ```typescript import {xSync} from 'tinyexec'; const result = xSync('echo', ['Hello, World!']); console.log(result.stdout); // "Hello, World!\n" console.log(result.exitCode); // 0 ``` -------------------------------- ### Get PATH from Environment Source: https://github.com/tinylibs/tinyexec/blob/main/_autodocs/module-architecture.md Extracts the PATH environment variable, handling case-insensitive keys which is important for Windows compatibility. ```typescript export function getPathFromEnv(env: EnvLike): EnvPathInfo { // Returns {key: 'PATH'|'Path'|..., value: '...'} } ``` -------------------------------- ### Execute and await a command Source: https://github.com/tinylibs/tinyexec/blob/main/README.md Spawn a process and await its completion. The result object contains stdout, stderr, and the exit code. ```ts import {x} from 'tinyexec'; const result = await x('ls', ['-l']); // result.stdout - the stdout as a string // result.stderr - the stderr as a string // result.exitCode - the process exit code as a number ``` -------------------------------- ### pid Source: https://github.com/tinylibs/tinyexec/blob/main/_autodocs/api-reference/execprocess-class.md Retrieves the process ID (PID) of the child process. Returns undefined if the process has not started or failed to spawn. ```APIDOC ## pid ### Description Retrieves the process ID (PID) of the child process. ### Type `number | undefined` ### Value The PID as a number, or undefined if the process hasn't started or failed to spawn. ### Example ```typescript const proc = x('sleep', ['10']); console.log('PID:', proc.pid); ``` ``` -------------------------------- ### Handle Spawn Errors with try-catch Source: https://github.com/tinylibs/tinyexec/blob/main/_autodocs/errors.md Shows how to use a try-catch block to handle potential spawn errors, specifically checking for the 'ENOENT' error code to identify if the command was not found. ```typescript import {x} from 'tinyexec'; try { const result = await x('mybinary', []); } catch (error) { if (error instanceof Error) { if ('code' in error && error.code === 'ENOENT') { console.log('Command not found'); } else { console.log('Spawn error:', error.message); } } } ``` -------------------------------- ### Access Process Properties During Execution Source: https://github.com/tinylibs/tinyexec/blob/main/_autodocs/quick-reference.md Get the process ID (PID), and check if the process has been killed or aborted during asynchronous execution. ```typescript const proc = x('command'); console.log(proc.pid); console.log(proc.killed); console.log(proc.aborted); ``` -------------------------------- ### Parametrized Tests with Vitest Source: https://github.com/tinylibs/tinyexec/blob/main/_autodocs/module-architecture.md Demonstrates how to set up parametrized tests using vitest to cover both asynchronous and synchronous execution variants. Ensure 'x' and 'xSync' are defined elsewhere in your test scope. ```typescript const variants = [ {name: 'async', x, isAsync: true}, {name: 'sync', x: xSync, isAsync: false} ]; describe.each(variants)('exec ($name)', ({x, isAsync}) => { // Tests run for both async and sync }); ``` -------------------------------- ### Catching NonZeroExitError with Imports Source: https://github.com/tinylibs/tinyexec/blob/main/_autodocs/errors.md Shows how to import NonZeroExitError and handle it within a try-catch block when executing a command like 'npm run build' with error throwing enabled. Includes logging the error code and stderr if available. ```typescript import {x, NonZeroExitError} from 'tinyexec'; try { const result = await x('npm', ['run', 'build'], {throwOnError: true}); } catch (error) { if (error instanceof NonZeroExitError) { console.error(`Build failed with exit code ${error.exitCode}`); if (error.output) { console.error('Stderr:', error.output.stderr); } } else { // Some other error (spawn failed, etc.) throw error; } } ``` -------------------------------- ### Disable nodePath for System Binaries Source: https://github.com/tinylibs/tinyexec/blob/main/_autodocs/configuration.md Execute a command without using the local `node_modules/.bin` directory. This forces the use of globally installed or system binaries. ```typescript import {x} from 'tinyexec'; // Use system eslint, not node_modules/.bin/eslint const result = await x('eslint', ['.'], { nodePath: false }); ``` -------------------------------- ### spawn() Source: https://github.com/tinylibs/tinyexec/blob/main/_autodocs/api-reference/execprocess-class.md Spawns the child process. This method is called automatically by the `x()` function. ```APIDOC ## spawn() Spawns the child process. Called automatically by the `x()` function. ### Signature ```typescript spawn(): void ``` ### Behavior - Creates the underlying Node.js child process via `child_process.spawn()`. - Sets up stdout/stderr streams. - Attaches event listeners for errors and process close. - Configures environment (including PATH augmentation if `nodePath` is true). - Applies abort signals for timeout or manual cancellation. ### Example ```typescript import {ExecProcess} from 'tinyexec'; const proc = new ExecProcess('echo', ['test']); proc.spawn(); const result = await proc; console.log(result.stdout); ``` ``` -------------------------------- ### Basic Command Execution Source: https://github.com/tinylibs/tinyexec/blob/main/_autodocs/api-reference/exec-function.md Execute a command and log its standard output and exit code. Ensure the command and its arguments are correctly provided. ```typescript import {x} from 'tinyexec'; const result = await x('ls', ['-l']); console.log(result.stdout); // directory listing console.log(result.exitCode); // 0 ``` -------------------------------- ### Execute a Command and Log Output Source: https://github.com/tinylibs/tinyexec/blob/main/_autodocs/README.md Run a command like 'ls -la' and access its standard output and exit code. Ensure the 'tinyexec' library is imported. ```typescript import {x} from 'tinyexec'; const result = await x('ls', ['-la']); console.log(result.stdout); console.log(result.exitCode); // 0 for success ``` -------------------------------- ### TinyExec Module Organization Source: https://github.com/tinylibs/tinyexec/blob/main/_autodocs/module-architecture.md Illustrates the directory structure of the tinyexec project, showing the location of core modules and test files. ```tree src/ ├── main.ts # Core execution logic ├── non-zero-exit-error.ts # Error class ├── normalize.ts # Windows command normalization ├── env.ts # Environment variable handling ├── stream.ts # Stream utilities └── test/ # Test files ├── main_test.ts ├── normalize_test.ts ├── env_test.ts └── stream_test.ts ``` -------------------------------- ### Providing Input via Stdin Source: https://github.com/tinylibs/tinyexec/blob/main/_autodocs/api-reference/exec-function.md Execute a command and provide input to its standard input stream. This is useful for commands that expect data piped into them. The input is provided as a string to the `stdin` option. ```typescript import {x} from 'tinyexec'; const result = await x('node', ['-e', 'process.stdin.pipe(process.stdout)'], { stdin: 'hello from stdin' }); console.log(result.stdout); // "hello from stdin" ``` -------------------------------- ### Executing Commands Without Node Modules in PATH Source: https://github.com/tinylibs/tinyexec/blob/main/_autodocs/api-reference/xsync-function.md Bypass the local 'node_modules/.bin' directory when searching for executables by setting 'nodePath: false'. This allows access to globally installed or system commands. ```typescript import {xSync} from 'tinyexec'; // Access system eslint, not local node_modules/.bin/eslint const result = xSync('eslint', ['.'], {nodePath: false}); ``` -------------------------------- ### Execute command from string using args-tokenizer Source: https://github.com/tinylibs/tinyexec/blob/main/README.md Parse a shell command string into an array of command and arguments using args-tokenizer, then execute it with tinyexec. ```ts import {x} from 'tinyexec'; import {tokenizeArgs} from 'args-tokenizer'; const commandString = 'echo "Hello, World!"'; const [command, ...args] = tokenizeArgs(commandString); const result = await x(command, args); result.stdout; // Hello, World! ``` -------------------------------- ### TinyExec Function (x) Source: https://github.com/tinylibs/tinyexec/blob/main/_autodocs/api-reference/exports-reference.md The main entry point function for executing commands. It takes command details and options, returning a `Result` object. ```APIDOC ## Function: TinyExec (x) ### Description This is the primary function used to execute shell commands. It accepts the command, arguments, and execution options, returning an asynchronous `Result`. ### Signature - **`x(command: string, args?: readonly string[], options?: Partial): Result`** - **`command`**: The command to execute. - **`args`**: Optional array of string arguments for the command. - **`options`**: Optional configuration for the execution, such as `timeout`, `throwOnError`, `signal`, etc. ``` -------------------------------- ### Handling NonZeroExitError from AsyncIterator Source: https://github.com/tinylibs/tinyexec/blob/main/_autodocs/errors.md When throwOnError is set to true, the async iterator will throw a NonZeroExitError if the child process exits with a non-zero status code. This example demonstrates how to catch and handle this specific error. ```typescript const proc = x('node', ['-e', 'process.exit(1)'], {throwOnError: true}); try { for await (const line of proc) { console.log(line); } } catch (error) { if (error instanceof NonZeroExitError) { console.log('Iterator threw:', error.exitCode); } } ``` -------------------------------- ### x Source: https://github.com/tinylibs/tinyexec/blob/main/_autodocs/api-reference/exports-reference.md Async execution function that runs a command and returns a Result. ```APIDOC ## x ### Description Async execution function that runs a command and returns a Result. ### Type `TinyExec` ### Returns `Result` ### File `src/main.ts:440` ``` -------------------------------- ### then(onfulfilled?, onrejected?) Source: https://github.com/tinylibs/tinyexec/blob/main/_autodocs/api-reference/execprocess-class.md Implements the PromiseLike interface to allow awaiting the process completion. ```APIDOC ## then(onfulfilled?, onrejected?) Implements the PromiseLike interface to allow awaiting the process completion. ### Signature ```typescript then( onfulfilled?: ((value: Output) => TResult1 | PromiseLike) | null, onrejected?: ((reason: unknown) => TResult2 | PromiseLike) | null ): Promise ``` ### Behavior Waits for the process to complete and resolves with the full `Output` object. ### Example ```typescript const proc = x('echo', ['hello']); proc.then( (output) => console.log('Success:', output.stdout), (error) => console.error('Failed:', error) ); ``` ``` -------------------------------- ### Using the Result Object Source: https://github.com/tinylibs/tinyexec/blob/main/_autodocs/types.md Demonstrates how to use the Result object as a promise, an async iterable, and to access process properties before awaiting. ```typescript const proc = x('ls', ['-la']); // As a promise const output: Output = await proc; // As async iterable for await (const line of proc) { console.log(line); } // Access properties before awaiting console.log(proc.pid); console.log(proc.killed); ``` -------------------------------- ### Sync Error Handling with xSync Source: https://github.com/tinylibs/tinyexec/blob/main/_autodocs/api-reference/non-zero-exit-error.md Illustrates how to catch NonZeroExitError when using the synchronous xSync function and accessing the exit code. ```typescript import {xSync, NonZeroExitError} from 'tinyexec'; try { const result = xSync('node', ['invalid.js'], {throwOnError: true}); } catch (error) { if (error instanceof NonZeroExitError) { console.error(`Exit code: ${error.exitCode}`); // Note: error.output will be the result object (same structure) } } ``` -------------------------------- ### exec Source: https://github.com/tinylibs/tinyexec/blob/main/_autodocs/api-reference/exports-reference.md Alias for the `x` function, providing identical behavior for asynchronous command execution. ```APIDOC ## exec ### Description Alias for `x`. Provides identical behavior for asynchronous command execution. ### Type `TinyExec` ### Behavior Identical to `x()` ### File `src/main.ts:448` ``` -------------------------------- ### pipe(command[, args[, options]]) Source: https://github.com/tinylibs/tinyexec/blob/main/README.md Pipes the current command to another command, allowing for chained execution. The parameters include the command to execute, an array of arguments, and an optional options object. ```APIDOC ## pipe(command[, args[, options]]) ### Description Pipes the current command to another. ### Parameters #### Path Parameters - **command** (string) - Required - the command to execute (_without any arguments_) - **args** (Array) - Optional - an array of arguments - **options** (object) - Optional - options object ``` -------------------------------- ### Default Sync Options Source: https://github.com/tinylibs/tinyexec/blob/main/_autodocs/configuration.md Specifies the default configuration for synchronous execution (`xSync`). Includes default values for `timeout` options, as well as default `SpawnSyncOptions` for the child process. ```typescript const defaultSyncOptions: Partial = { timeout: undefined }; const defaultNodeOptions: SpawnSyncOptions = { windowsHide: true }; ``` -------------------------------- ### Configure Command Execution Options Source: https://github.com/tinylibs/tinyexec/blob/main/_autodocs/quick-reference.md Customize command execution with options such as timeout, error handling, input, and Node.js spawn options. ```typescript const result = await x('cmd', ['args'], { timeout: 5000, throwOnError: true, nodePath: true, signal: abortController.signal, stdin: 'input string', persist: false, nodeOptions: {cwd: '/path'} }); ``` -------------------------------- ### Process Monitoring Source: https://github.com/tinylibs/tinyexec/blob/main/_autodocs/api-reference/execprocess-class.md Shows how to monitor a running process, access its PID, and iterate over its output line by line, checking for errors and the final exit code. ```APIDOC ## Process Monitoring ### Description Monitor a running process. You can access the `pid` immediately after creation. You can iterate over the process instance to receive output line by line. After the process finishes, you can access the `exitCode`. ### Usage ```typescript import {x} from 'tinyexec'; const proc = x('docker', ['build', '.']); console.log('Starting process, PID:', proc.pid); for await (const line of proc) { if (line.includes('error')) { console.error('Build error:', line); } } console.log('Build exit code:', proc.exitCode); ``` ### Related - [x function](./exec-function.md) - [Result type](./types.md#result) ``` -------------------------------- ### Monitor Process Execution Source: https://github.com/tinylibs/tinyexec/blob/main/_autodocs/api-reference/execprocess-class.md Illustrates how to monitor a running process using an async iterator. This allows for real-time processing of output lines and checking the exit code after completion. ```typescript import {x} from 'tinyexec'; const proc = x('docker', ['build', '.']); console.log('Starting process, PID:', proc.pid); for await (const line of proc) { if (line.includes('error')) { console.error('Build error:', line); } } console.log('Build exit code:', proc.exitCode); ``` -------------------------------- ### Import Tinyexec Functions Source: https://github.com/tinylibs/tinyexec/blob/main/_autodocs/quick-reference.md Import the necessary functions and classes from the tinyexec library for execution and error handling. ```typescript import { x, exec, xSync, execSync, ExecProcess, NonZeroExitError } from 'tinyexec'; ``` -------------------------------- ### pipe(command, args?, options?) Source: https://github.com/tinylibs/tinyexec/blob/main/_autodocs/api-reference/execprocess-class.md Chains this process's output to another command. Returns a new Result object for the piped command. ```APIDOC ## pipe(command, args?, options?) Chains this process's output to another command. ### Signature ```typescript pipe( command: string, args?: readonly string[], options?: Partial ): Result ``` ### Parameters - **command** (string) - Required - The command to pipe to. - **args** (readonly string[], optional) - Arguments for the piped command. - **options** (Partial, optional) - Options for the piped command (same as for `x()`). ### Returns A new `Result` object for the piped command. ### Behavior - Automatically passes this process's stdout to the piped command's stdin. - The piped command is a new `Result` that can be further piped. - Options passed to `pipe()` apply only to the piped command. ### Example ```typescript const result = await x('ls', ['-la']) .pipe('grep', ['.js']) .pipe('wc', ['-l']); console.log('Count of .js files:', result.stdout); ``` With timeout on the pipe: ```typescript const result = await x('cat', ['large-file.txt']) .pipe('grep', ['pattern'], {timeout: 5000}); ``` ``` -------------------------------- ### Basic Sync Execution Source: https://github.com/tinylibs/tinyexec/blob/main/_autodocs/configuration.md Executes a command synchronously and logs its standard output and exit code. ```typescript import {xSync} from 'tinyexec'; const result = xSync('echo', ['Hello']); console.log(result.stdout); // "Hello\n" console.log(result.exitCode); // 0 ``` -------------------------------- ### Accessing Result and Output from NonZeroExitError Source: https://github.com/tinylibs/tinyexec/blob/main/_autodocs/api-reference/non-zero-exit-error.md Demonstrates how to access both the result (pid, killed) and output (stdout, stderr) properties from a NonZeroExitError. ```typescript import {x, NonZeroExitError} from 'tinyexec'; try { await x('node', ['script.js'], {throwOnError: true}); } catch (error) { if (error instanceof NonZeroExitError) { // From result (always present) console.log('PID:', error.result.pid); console.log('Killed:', error.result.killed); // From output (async only) if (error.output) { console.log('Stdout:', error.output.stdout); console.log('Stderr:', error.output.stderr); } } } ``` -------------------------------- ### Handling NonZeroExitError in Async Operations Source: https://github.com/tinylibs/tinyexec/blob/main/_autodocs/errors.md Demonstrates how to catch and inspect a NonZeroExitError when a process exits with a non-zero code and throwOnError is true. Shows how to access the exit code and potentially the output. ```typescript const result = await x('false'); console.log(result.exitCode); // 1 ``` ```typescript try { await x('false', [], {throwOnError: true}); } catch (error) { if (error instanceof NonZeroExitError) { console.log(error.exitCode); // 1 } } ``` -------------------------------- ### x() and exec() - Async Execution Function Source: https://github.com/tinylibs/tinyexec/blob/main/_autodocs/DOCUMENTATION_SUMMARY.txt The `x()` function, aliased as `exec()`, provides asynchronous execution of commands. It returns a promise that resolves with the execution result. ```APIDOC ## x() and exec() ### Description Asynchronous execution function for commands. Returns a promise that resolves with the execution result. ### Method Async function call ### Endpoint N/A (SDK Function) ### Parameters Refer to `CommonOptions` and `Options` for available parameters. ### Request Example ```javascript const result = await x('ls', ['-l']); console.log(result.stdout); ``` ### Response #### Success Response - **stdout** (string) - Standard output of the command. - **stderr** (string) - Standard error of the command. - **exitCode** (number) - The exit code of the command. - **killed** (boolean) - Whether the process was killed. - **aborted** (boolean) - Whether the process was aborted. #### Response Example ```json { "stdout": "total 0\n-rw-r--r-- 1 user group 0 Jan 1 00:00 file.txt", "stderr": "", "exitCode": 0, "killed": false, "aborted": false } ``` ``` -------------------------------- ### Execute and Pipe Command Source: https://github.com/tinylibs/tinyexec/blob/main/README.md Use the `pipe` method to chain commands, sending the output of the first command as input to the second. The `command` parameter should not include arguments. ```typescript x('ls', ['-l']) .pipe('grep', ['js']); ``` -------------------------------- ### Handling NonZeroExitError Source: https://github.com/tinylibs/tinyexec/blob/main/_autodocs/api-reference/non-zero-exit-error.md Demonstrates how NonZeroExitError is thrown when `throwOnError` is true and a process exits with a non-zero code. Also shows that the error is not thrown if `throwOnError` is false, allowing access to the exit code. ```typescript // Never throws, just check the property const proc = x('false'); const result = await proc; console.log(result.exitCode); // 1, no error thrown // Throws NonZeroExitError try { await x('false', [], {throwOnError: true}); } catch (error) { // error instanceof NonZeroExitError is true } ``` -------------------------------- ### Real-Time Output Monitoring Source: https://github.com/tinylibs/tinyexec/blob/main/_autodocs/integration-patterns.md React to command output patterns as they appear. Ideal for real-time monitoring and interactive applications. ```typescript import {x} from 'tinyexec'; async function monitorBuild() { const proc = x('npm', ['run', 'build']); let errorCount = 0; let warningCount = 0; for await (const line of proc) { if (line.includes('ERROR')) { errorCount++; console.error('Build error:', line); } else if (line.includes('WARNING')) { warningCount++; console.warn('Build warning:', line); } else { console.log(line); } } console.log(`Build complete: ${errorCount} errors, ${warningCount} warnings`); } ``` -------------------------------- ### Execution Options Source: https://github.com/tinylibs/tinyexec/blob/main/_autodocs/quick-reference.md Customize command execution using an options object. Options include setting timeouts, controlling error handling, modifying the PATH, providing cancellation signals, setting stdin, and configuring Node.js spawn options. ```APIDOC ## Execution Options ### Description Customize command execution behavior using an options object. ### Options - **timeout** (number) - The timeout in milliseconds. The process will be killed after this duration. - **throwOnError** (boolean) - If true, throws a `NonZeroExitError` when the command exits with a non-zero code (default: false). - **nodePath** (boolean) - If true, adds `./node_modules/.bin` to the PATH (default: true). - **signal** (AbortSignal) - An `AbortSignal` to cancel the execution. - **stdin** (string) - Input to be provided to the standard input of the process. - **persist** (boolean) - If true, the process will continue running even after the parent process exits (default: false). - **nodeOptions** (object) - Options to be passed to Node.js `child_process.spawn`. ### Usage Example ```typescript const abortController = new AbortController(); const result = await x('cmd', ['args'], { timeout: 5000, throwOnError: true, nodePath: true, signal: abortController.signal, stdin: 'input string', persist: false, nodeOptions: { cwd: '/path' } }); ``` ``` -------------------------------- ### API Reference normalizeSpawnCommand Function Source: https://github.com/tinylibs/tinyexec/blob/main/_autodocs/DOCUMENTATION_SUMMARY.txt Documentation for the `normalizeSpawnCommand` function, which normalizes command arguments for cross-platform compatibility. ```APIDOC ## normalizeSpawnCommand(command, options) ### Description Normalizes the command and arguments to ensure consistent behavior across different platforms (Windows, Unix-like systems). ### Method `normalizeSpawnCommand(command, options)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **command** (string | string[]) - Required - The command to normalize. - **options** (CommonOptions) - Optional - Options that may affect normalization. ``` -------------------------------- ### xSync Source: https://github.com/tinylibs/tinyexec/blob/main/_autodocs/api-reference/exports-reference.md Synchronous execution function that runs a command and returns a SyncResult without a Promise. ```APIDOC ## xSync ### Description Synchronous execution function that runs a command and returns a SyncResult (not a Promise). ### Signature ```typescript export function xSync( command: string, args?: readonly string[], options?: Partial ): SyncResult ``` ### Returns `SyncResult` (not a Promise) ### File `src/main.ts:376` ``` -------------------------------- ### Configure Working Directory and Environment Source: https://github.com/tinylibs/tinyexec/blob/main/_autodocs/integration-patterns.md Set a custom working directory (cwd) and environment variables for a child process. This is useful for monorepos or builds requiring specific configurations. ```typescript import {x} from 'tinyexec'; async function runInSubdirectory() { const result = await x('npm', ['run', 'build'], { nodeOptions: { cwd: './packages/my-app', env: { ...process.env, NODE_ENV: 'production' } } }); console.log(result.stdout); } ``` -------------------------------- ### Handle Command Errors with Fallback Source: https://github.com/tinylibs/tinyexec/blob/main/_autodocs/quick-reference.md Use the `.catch()` method to provide an alternative command or action if the primary command fails. This is useful for error recovery or using fallback strategies. ```typescript const result = await x('npm', ['install']) .catch(() => x('npm', ['install', '--legacy-peer-deps'])); ``` -------------------------------- ### Execute Piped Commands with Different Timeouts Source: https://github.com/tinylibs/tinyexec/blob/main/_autodocs/configuration.md Demonstrates executing a command pipeline where each command in the pipe has its own independent timeout configuration. ```typescript const result = await x('find', ['.', '-type', 'f'], { timeout: 10000 // Timeout for find }) .pipe('grep', ['pattern'], { timeout: 5000 // Different timeout for grep }); ``` -------------------------------- ### Catching NonZeroExitError Source: https://github.com/tinylibs/tinyexec/blob/main/_autodocs/api-reference/non-zero-exit-error.md Demonstrates how to catch a NonZeroExitError and access its exitCode and stderr properties. ```typescript import {x, NonZeroExitError} from 'tinyexec'; try { const result = await x('npm', ['run', 'build'], {throwOnError: true}); console.log('Build succeeded'); } catch (error) { if (error instanceof NonZeroExitError) { console.error('Build failed'); console.error('Exit code:', error.exitCode); console.error('Error output:', error.output?.stderr); } else { console.error('Unexpected error:', error); } } ``` -------------------------------- ### NonZeroExitError Class Source: https://github.com/tinylibs/tinyexec/blob/main/_autodocs/api-reference/non-zero-exit-error.md Details of the NonZeroExitError class, including its constructor parameters, properties, and inherited members. ```APIDOC ## Class: NonZeroExitError Custom error class thrown when a process exits with a non-zero code and the `throwOnError` option is enabled. ### Constructor **Parameters:** - **result** (`CommonOutputApi`) - Required - The process result object with `pid`, `killed`, `exitCode` properties. - **output** (`Output`) - Optional - The complete output object (stdout, stderr, exitCode). Present when thrown from async execution, absent from sync. ### Properties - **result** (`CommonOutputApi`) - `pid?: number` - `killed: boolean` - `exitCode?: number` - Description: The process result that triggered the error. - **output** (`Output`) - `stdout: string` - `stderr: string` - `exitCode?: number` - Description: The complete output object (stdout, stderr, exitCode). Only present for async execution. - **exitCode** (`number | undefined`) - Description: Getter for the exit code from the result. - **name** (`"NonZeroExitError"`) - Description: The error name is always "NonZeroExitError". - **message** (`string`) - Description: Standard error message with the exit code. - Format: "Process exited with non-zero status ({exitCode})" ``` -------------------------------- ### Batch Operations with Promise.all Source: https://github.com/tinylibs/tinyexec/blob/main/_autodocs/README.md Execute multiple commands concurrently using Promise.all. This is efficient for running independent tasks in parallel, such as linting, building, and testing. ```typescript const results = await Promise.all([ x('npm', ['run', 'lint']), x('npm', ['run', 'build']), x('npm', ['test']) ]); ``` -------------------------------- ### Importing tinyexec Exports Source: https://github.com/tinylibs/tinyexec/blob/main/_autodocs/api-reference/exports-reference.md Import all necessary functions and types from the tinyexec package for use in your project. ```typescript import { x, exec, xSync, execSync, ExecProcess, NonZeroExitError, normalizeSpawnCommand, // Types: Output, Result, SyncResult, Options, SyncOptions, CommonOptions, PipeOptions, OutputApi, OutputApiSync, CommonOutputApi, KillSignal, TinyExec } from 'tinyexec'; ``` -------------------------------- ### TinyExec Module Dependency Graph Source: https://github.com/tinylibs/tinyexec/blob/main/_autodocs/module-architecture.md Visualizes the dependencies between the core modules of tinyexec, highlighting the public API and inter-module relationships. ```graphviz digraph { rankdir=TB; node [shape=box]; main [label="main.ts (public API)\n x(), xSync(), ExecProcess, exports"]; env [label="env.ts"]; normalize [label="normalize.ts"]; stream [label="stream.ts"]; error [label="non-zero-exit-error.ts\n(imported by main.ts)"]; main -> env; main -> normalize; main -> stream; error -> main [dir=back]; } ``` -------------------------------- ### Catching NonZeroExitError and Accessing Output Properties Source: https://github.com/tinylibs/tinyexec/blob/main/_autodocs/api-reference/non-zero-exit-error.md Shows how to catch a NonZeroExitError and access the `stdout` and `stderr` from the `output` property. The `output` property is only available for async executions. ```typescript try { const result = await x('grep', ['pattern', 'file.txt'], {throwOnError: true}); } catch (error) { if (error instanceof NonZeroExitError) { console.log('Output:', error.output?.stdout); console.log('Errors:', error.output?.stderr); } } ``` -------------------------------- ### Custom Node.js Spawn Options Source: https://github.com/tinylibs/tinyexec/blob/main/_autodocs/configuration.md Provide custom options to Node.js's `child_process.spawn` function. This allows fine-grained control over execution environment and I/O. ```typescript import {x} from 'tinyexec'; const result = await x('node', ['script.js'], { nodeOptions: { cwd: '/some/directory', // Working directory env: {PATH: '/custom/path'}, // Environment variables stdio: ['ignore', 'pipe', 'pipe'], // stdin, stdout, stderr shell: true // Use shell } }); ``` -------------------------------- ### Default Async Options Source: https://github.com/tinylibs/tinyexec/blob/main/_autodocs/configuration.md Specifies the default configuration for asynchronous execution (`x`). Includes default values for `timeout` and `persist` options, as well as default `SpawnOptions` for the child process. ```typescript const defaultOptions: Partial = { timeout: undefined, persist: false }; const defaultNodeOptions: SpawnOptions = { windowsHide: true }; ```