Node.js › Advanced Node.js

How does Node.js implement the Worker Threads module differently from Child Processes, and when should each be used?

Advanced

Answer

Worker threads (node:worker_threads) run genuine OS threads within the same process, sharing memory via SharedArrayBuffer and communicating cheaply via structured-clone message passing -- ideal for CPU-bound work like image processing or complex calculations that would otherwise block the event loop. Child processes (node:child_process) spawn entirely separate OS processes with isolated memory, heavier startup cost, and communication only via serialized IPC or stdio -- better suited for running external programs or isolating untrusted/crash-prone code.
const { Worker } = require('node:worker_threads');
const worker = new Worker('./cpu-intensive-task.js', { workerData: { n: 40 } });
worker.on('message', (result) => console.log('Fibonacci result:', result));

// vs. child_process for running a separate program
const { spawn } = require('node:child_process');
spawn('python3', ['script.py']);
Real-world example An image-resizing API offloads the actual pixel-processing work to a pool of worker threads so the main event loop stays free to accept new HTTP requests, while a separate video-transcoding service uses child_process.spawn to run ffmpeg as an isolated external process instead.

Common follow-ups: Why is memory isolation in child processes sometimes an advantage rather than a limitation?;What data types can and can't be passed directly between worker threads without serialization?