Child Processes

๐ŸŸข Node.js LTS ๐Ÿ“— Chapter 37 of 49 ๐Ÿ“‚ Phase 11: Real-Time & Advanced ๐Ÿ—“๏ธ 2026 Edition
๐Ÿ“Œ Covered in this chapter: exec vs spawn vs fork ยท Running Shell Commands ยท Process Communication ยท Security

Spawn and communicate with external OS processes from Node.js using exec, spawn, and fork.

1Child Processes โ€” What You'll Learn

Spawn and communicate with external OS processes from Node.js using exec, spawn, and fork.

Here's everything this chapter covers, in the order you'll learn it:

  • What a child process is
  • exec() for running shell commands and capturing output
  • spawn() for streaming large output
  • fork() for spawning another Node.js process
  • Reading process output
  • Handling process errors
  • Security risks of shell execution
  • Preventing command injection
  • Communicating between parent and child processes
2Working Example
๐Ÿ’ป Example: Child Processes
import { exec } from "node:child_process";

exec("node --version", (error, stdout, stderr) => {
  if (error) {
    console.error(error.message);
    return;
  }
  console.log("Node version:", stdout.trim());
});
3Best Practices & Common Pitfalls
๐Ÿ’ก Key things to remember:
  • Never pass unsanitized user input directly into exec() โ€” it runs through a shell and is vulnerable to command injection. Prefer spawn() with an argument array instead.
โ“ Frequently Asked Questions (FAQ)

Q What's the most important thing to understand about child processes?

Focus on: exec vs spawn vs fork ยท Running Shell Commands ยท Process Communication ยท Security. These are the core building blocks this chapter's examples are built around, and they show up repeatedly in later chapters of this course.

Q Do I need external npm packages for child processes?

Only where explicitly shown in the code examples above (like Express, Zod, or Socket.IO) โ€” otherwise, this chapter relies entirely on Node.js's own built-in capabilities.

OC
Written by Our Compiler Technical Editorial Team
Reviewed for accuracy & tested on Node.js LTS ยท Last updated August 2026