child_process.spawn() and execFile()
Child processes execute a separate program with their own process identity and memory. Node offers spawn for streamed process I/O, execFile for buffered execution of a program, exec for shell commands, and fork for a Node module with an IPC channel. Use a fixed reviewed executable and a separate argument array with shell disabled. This avoids shell parsing of argument text, but does not make arbitrary executable options or programs safe; validate allowed inputs. The error event can indicate spawn failure, exit reports the process termination, and close reports termination plus closed stdio streams. For buffered execFile output, set maxBuffer and a timeout. For streaming spawn, consume or redirect stdout and stderr, cap output and define a deadline. Use process.execPath for this lab, a fixed script, and a minimal environment. Process separation alone is not a hostile-code sandbox. Avoid interpolating request values into shell strings. Do not use a command runner as a general web endpoint. Do not assume exit code zero guarantees the business result; test the output contract. Sources: https://nodejs.org/download/release/v22.16.0/docs/api/child_process.html.
Formal Syntax & Structure
spawn(command[, args][, options]); execFile(file[, args][, options][, callback])Working Example
import {spawn} from 'node:child_process';import {once} from 'node:events';const child=spawn(process.execPath,['task.mjs','two books'],{shell:false,stdio:['ignore','pipe','pipe'],env:{LANG:'C.UTF-8'}});const finished=once(child,'close');let output='',errors='';child.stdout.setEncoding('utf8');child.stdout.on('data',c=>output+=c);child.stderr.on('data',c=>errors+=c);const timer=setTimeout(()=>child.kill(),1500);try {const [code]=await finished;console.log(output.trim());console.log('exit',code,'stderr',errors.length);}finally{clearTimeout(timer);if(child.exitCode===null&&child.signalCode===null)child.kill();}