Courses / Node.js: From First Script to Production / Chapter 10
Module 5 · Packages, databases and advanced topics · Chapter 10 of 27
Advanced Topics: Child Processes, Worker Threads, Cluster and Debugging
Builds on Asynchronous Programming: Callbacks, Promises and async/await, Event-Driven Programming with EventEmitter, Core Modules: Files, Paths, Buffers, Crypto and util and Building a Basic Web Server with node:http. Next up: Inside the Event Loop: Phases, Timers and setImmediate.
Part 1 · Running other programs: spawn, exec, execFile and fork
A child process is a separate program
An image resizer, a PDF report and a video thumbnailer are jobs that should not run on your request thread. Node gives you three ways to move them out: other processes, worker threads and a cluster.
A child process is a separate operating-system process that your Node program starts. It has its own memory, its own process id and, if it is another Node program, its own event loop. If it crashes, your program carries on. That isolation is the reason to use one: you can run a command-line tool such as git or ffmpeg, run work that might fail badly, or put a second copy of Node on another CPU core.
The node:child_process module has four main functions. They differ in three ways: whether the command goes through a shell, whether the output is streamed or collected, and whether the child can talk back over a message channel.