Skip to content
Node.js

Child Process

Spawn, exec, and fork external processes.

By EZ4Code Team
child-processspawnexec

Code

import { spawn, exec, execFile, fork } from "child_process";

// spawn: streaming for large output
const ls = spawn("ls", ["-la", "/var/log"]);
ls.stdout.on("data", d => process.stdout.write(d));
ls.stderr.on("data", d => process.stderr.write(d));
ls.on("close", code => console.log("exit", code));

// exec: buffered, single callback, use for short output
exec("du -sh /var/log", (err, stdout, stderr) => {
  if (err) throw err;
  console.log(stdout.trim());
});

// execFile: like exec but no shell (safer with user input)
execFile("git", ["status"], (err, stdout) => console.log(stdout));

// fork: spawn a Node child with an IPC channel
const child = fork("./worker.js");
child.send({ job: "compress", file: "input.bin" });
child.on("message", msg => console.log("child said", msg));

// Promisified exec via util.promisify
import util from "util";
const execP = util.promisify(exec);
const { stdout } = await execP("node --version");

Explanation

spawn streams child stdio and is ideal for long-running processes with large output. exec buffers output and runs through a shell, so never pass unsanitized user input to it—use execFile instead. fork spawns a Node process with a built-in IPC channel, the basis for Node's cluster module.

More Node.js Snippets