Working with Child Processes

1. Executing Commands (child_process.exec)

Example

import { exec } from "node:child_process";
import { promisify } from "node:util";
const { stdout } = await promisify(exec)("git rev-parse HEAD");
Warning: Never interpolate user input into a shell string — use execFile/spawn with array args.

2. Executing Files (child_process.execFile)

Example

execFile("ls", ["-l", "/tmp"], (err, stdout) => { /* ... */ });
Diff vs execDetail
No shellSafer, faster
Args as arrayNo injection

3. Spawning Processes (child_process.spawn)

Example: Stream stdout

const cp = spawn("ffmpeg", ["-i", "in.mp4", "out.mp3"]);
cp.stdout.pipe(process.stdout);
cp.on("exit", (code) => console.log("done", code));

4. Forking Processes (child_process.fork)

APIUse
fork(modulePath, args)Spawn another Node process
IPCAuto-set up via process.send / "message"

5. Handling Child Process Events

EventFires
spawnProcess started
exitProcess exited (no streams flushed yet)
closeAll stdio closed
errorCouldn't spawn
messageIPC (only with fork / { stdio: "ipc" })

6. Piping Standard I/O

stdio OptionEffect
"pipe"Default; cp.stdout available
"inherit"Share parent's stdio
"ignore"Drop output
ArrayPer-stream config (e.g. ["pipe","inherit","pipe"])

7. Communicating with IPC

Example

// parent
const child = fork("./worker.js");
child.send({ task: "compute", n: 100 });
child.on("message", (msg) => console.log("result", msg));
// worker.js
process.on("message", (m) => process.send({ ok: true, value: m.n * 2 }));

8. Setting Working Directory

OptionUse
cwd: "/path"Run in a specific dir

9. Configuring Environment Variables

OptionUse
env: { ...process.env, FOO: "1" }Inherit + override
env: { FOO: "1" }Replace fully

10. Detaching Child Processes

Example: Long-running daemon

const cp = spawn("node", ["server.js"], {
  detached: true,
  stdio: "ignore"
});
cp.unref(); // parent can exit

11. Killing Child Processes

APIEffect
cp.kill("SIGTERM")Default polite termination
cp.kill("SIGKILL")Force kill
cp.killedBoolean

12. Using Promisified Exec (util.promisify)

HelperUse
promisify(exec)Returns {stdout, stderr}
execa (npm)Better defaults, cross-platform