TypeScript

Distinction: Node.js Child Process vs. Node.js Worker

Node.js is single-threaded. When you need to do CPU-heavy or parallel work, you have two options: child processes and worker threads. They solve different...

29 Apr 2024

Distinction: Node.js Child Process vs. Node.js Worker

Node.js is single-threaded. When you need to do CPU-heavy or parallel work, you have two options: child processes and worker threads. They solve different problems.

Child Process — a separate Node.js instance

A child process spawns an entirely new Node.js runtime. It has its own memory, its own event loop, its own everything. Communication happens through message passing.

Use it for CPU-intensive work, executing external commands, or anything that needs full isolation.

Text
import { fork } from 'child_process';
const childProcess = fork('./childProcess.ts');

childProcess.on('message', (message) => {
  console.log('Sum computed by child process:', message);
});

childProcess.send({ numbers: [1, 2, 3, 4, 5] });
Text
// childProcess.ts
process.on('message', (data) => {
  const sum = data.numbers.reduce((acc, num) => acc + num, 0);
  process.send(sum);
});

Worker Thread — a thread inside the same process

Worker threads run inside the same Node.js process. They share memory with the main thread and are lighter than child processes.

Use them for parallelizing I/O-bound work — network requests, database queries, file system operations.

Text
import { Worker, isMainThread } from 'worker_threads';
if (isMainThread) {
  const worker = new Worker('./workerThread.ts');

  worker.on('message', (message) => {
    console.log('Result received from worker thread:', message);
  });
  worker.postMessage({ data: 'example data' });
}
Text
import { parentPort } from 'worker_threads';

const performTask = () => {
  setTimeout(() => {
    const result = 'Processed data';
    parentPort.postMessage(result);
  }, 2000);
};

performTask();

When to use which

Child processes: Blocking operations, file I/O, executing shell commands, or when you need full isolation between tasks.

Worker threads: Async I/O parallelism within the same process. Lower overhead because they share memory — no separate runtime to boot up.

The trade-off

Child processes are heavier but safer — a crash in one doesn't take down your main process. Worker threads are lighter but share memory, which means a misbehaving thread can corrupt shared state.

Pick based on the problem. CPU isolation → child process. Lightweight parallelism → worker thread.

Keep reading