A modern, promise-based utility package for Node.js that provides enhanced child process execution with robust error handling, timeouts, and input streaming support.
exec-utils wraps Node.js child process functions with additional features that make command execution more reliable and convenient:
- Promise-based API - Clean async/await pattern for process execution
- Timeout support - Automatically kill long-running processes
- AbortSignal integration - Cancel operations from outside
- Input streaming - Easily pipe data to child processes
- Unified error handling - Consistent error format with exit codes
- Buffer size limits - Prevent memory issues with large outputs
- Configurable encoding - Control output encoding
- Typescript support - Full type definitions included
npm i exec-utilsnpm i https://github.com/lacherogwu/exec-utils- Node.js 16 or higher
import{spawn,exec}from'exec-utils';// Using spawn for commands with argumentsconst{ data }=awaitspawn('echo',['Hello','World']);console.log(data);// 'Hello World\n'// Using exec for shell commandsconst{data: execData}=awaitexec('echo "Hello World"');console.log(execData);// 'Hello World\n'// Kill process after 5 secondsconst{ error }=awaitspawn('sleep',['10'],{timeout: 5000});if(error){console.log(error.message);// "Command timed out after 5000ms"console.log(error.code);// -1}// Provide input to a commandconst{ data }=awaitspawn('grep',['good'],{input: 'no errors here\nthis line has an error\nall good',});console.log(data);// 'all good\n'// JSON processing with jqconst{data: jsonData}=awaitspawn('jq',['.name'],{input: JSON.stringify({name: 'John',age: 30}),});console.log(jsonData.trim());// '"John"'// Cancel execution from outsideconstcontroller=newAbortController();const{ signal }=controller;// Start a processconstprocessPromise=spawn('sleep',['10'],{ signal });// Cancel it after 2 secondssetTimeout(()=>{controller.abort();},2000);const{ error }=awaitprocessPromise;if(error){console.log(error.message);// "Operation aborted"console.log(error.code);// -1}// Handle errors and non-zero exit codesconst{ error, data }=awaitspawn('ls',['non-existent-directory']);if(error){console.error(`Command failed with code ${error.code}`);console.error(error.message);// Contains stderr output}else{console.log(data);}Executes a command with arguments.
- Parameters:
command: Command to executeargs: Array of argumentsoptions: Optional configuration object
- Returns:
- Promise resolving to a
CommandResultobject
- Promise resolving to a
Executes a shell command.
- Parameters:
command: Shell command to executeoptions: Optional configuration object
- Returns:
- Promise resolving to a
CommandResultobject
- Promise resolving to a
interfaceSpawnOptions{// Timeout in millisecondstimeout?: number;// Maximum buffer size in bytes (default: 80MB)maxBuffer?: number;// Output encoding (default: 'utf8')encoding?: BufferEncoding;// AbortSignal for cancellationsignal?: AbortSignal;// Data to write to stdininput?: string|Buffer|NodeJS.ReadableStream;// Plus all Node.js child_process.SpawnOptions}interfaceExecOptions{// Same as SpawnOptions plus all Node.js child_process.ExecOptions}typeCommandResult=|{// Process succeededdata: string;// Process output as stringdataAsBuffer: Buffer;// Raw output buffererror: null;// No errorprocess: ChildProcess;// Process reference}|{// Process faileddata: null;// No datadataAsBuffer: null;// No data buffererror: ExecUtilsError;// Error with message and codeprocess: ChildProcess;// Process reference};MIT