Worker threads and child processes help Node.js run tasks at the same time without waiting. They make your app faster by doing work in the background.
Worker thread vs child process in Node.js
const { Worker } = require('worker_threads');
const worker = new Worker('./worker.js');
worker.on('message', (msg) => {
console.log('From worker:', msg);
});
worker.postMessage('start');
// For child process
const { fork } = require('child_process');
const child = fork('./child.js');
child.on('message', (msg) => {
console.log('From child:', msg);
});
child.send('start');Worker threads share memory with the main thread but run code in parallel.
Child processes run completely separate programs and communicate via messages.
const { Worker } = require('worker_threads');
const worker = new Worker(`
const { parentPort } = require('worker_threads');
parentPort.on('message', (msg) => {
parentPort.postMessage(`Hello, ${msg}`);
});
`, { eval: true });
worker.on('message', (msg) => console.log(msg));
worker.postMessage('World');const { fork } = require('child_process');
const child = fork('child.js');
child.on('message', (msg) => console.log(msg));
child.send('ping');
// child.js
process.on('message', (msg) => {
process.send(`pong to ${msg}`);
});This program shows both a worker thread and a child process doing a heavy calculation separately. Both send results back to the main app.
const { Worker } = require('worker_threads');
const { fork } = require('child_process');
// Worker thread example
const worker = new Worker(`
const { parentPort } = require('worker_threads');
parentPort.on('message', (msg) => {
// Simulate heavy work
let count = 0;
for(let i=0; i<1e7; i++) count += i;
parentPort.postMessage(`Worker done: ${count}`);
});
`, { eval: true });
worker.on('message', (msg) => {
console.log(msg);
});
worker.postMessage('start');
// Child process example
const child = fork('./child.js');
child.on('message', (msg) => {
console.log(msg);
});
child.send('start');
// child.js content:
// process.on('message', (msg) => {
// // Simulate separate task
// let sum = 0;
// for(let i=0; i<1e7; i++) sum += i;
// process.send(`Child done: ${sum}`);
// });Worker threads are better for CPU-heavy tasks inside the same app.
Child processes are good for running separate programs or scripts.
Communication between them uses messages, so data is copied, not shared (except worker threads can share memory with special objects).
Worker threads run code in parallel inside the same app and share memory.
Child processes run separate programs and communicate by sending messages.
Use them to keep your app fast and responsive during heavy or separate tasks.