child_process

The child_process module allows running other programs from within your application. It provides ways to spawn new processes, run commands, and communicate with them.


API Surface

Process Creation

  • spawn(command, args?, options?) — launch a new process with streams for I/O.
  • exec(command, options?, callback) — run a command in a shell, buffer output.
  • execFile(file, args?, options?, callback) — run executable file directly, no shell.
  • fork(modulePath, args?, options?) — spawn new Node/Bnlang process with IPC channel.

Synchronous Variants

  • spawnSync(command, args?, options?)
  • execFileSync(file, args?, options?)
  • execSync(command, options?)

ChildProcess Object

  • Streams: .stdin, .stdout, .stderr.
  • Events: 'exit', 'error', 'close'.
  • Properties: .pid, .killed.
  • Methods: .kill([signal]).

Examples (English only)

const { spawn, exec, fork } = require("child_process");

// spawn: stream output
const ls = spawn("ls", ["-l"]);
ls.stdout.on("data", (data) => console.log("stdout:", data.toString()));
ls.stderr.on("data", (data) => console.error("stderr:", data.toString()));
ls.on("close", (code) => console.log("child exited with", code));

// exec: buffered output
exec("echo Hello", (err, stdout, stderr) => {
  if (err) throw err;
  console.log("exec output:", stdout);
});

// fork: run another JS module with IPC
const child = fork("worker.js");
child.on("message", (msg) => console.log("From child:", msg));
child.send({ hello: "world" });

Notes

  • spawn is best for streaming large output.
  • exec buffers output, risk of exceeding memory with huge output.
  • execFile avoids shell, safer for fixed binaries.
  • fork is optimized for spawning another runtime script with messaging.
  • Always handle errors and exit codes to avoid zombie processes.