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
Start learning this pattern below
Jump into concepts and practice - no test required
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.
Practice
worker threads and child processes in Node.js?Solution
Step 1: Understand worker threads behavior
Worker threads run JavaScript code in parallel but inside the same Node.js process and share memory.Step 2: Understand child processes behavior
Child processes run completely separate programs with their own memory space and communicate via messages.Final Answer:
Worker threads run in the same process sharing memory, while child processes run in separate processes with separate memory. -> Option AQuick Check:
Worker threads share memory, child processes do not [OK]
- Confusing memory sharing between threads and processes
- Thinking child processes share memory
- Assuming worker threads run separate programs
Solution
Step 1: Recall worker thread creation syntax
Worker threads are created using theWorkerclass from theworker_threadsmodule.Step 2: Identify correct constructor usage
The correct syntax isnew Worker('filename'). Theforkandspawnmethods are for child processes.Final Answer:
const worker = new Worker('worker.js'); -> Option DQuick Check:
Worker threads usenew Worker()[OK]
- Using fork() to create worker threads
- Using spawn() for worker threads
- Using non-existent createThread() function
const { fork } = require('child_process');
const child = fork('child.js');
child.on('message', msg => console.log('Parent got:', msg));
child.send('Hello');What will the parent process output if
child.js sends back { reply: 'Hi' } on receiving a message?Solution
Step 1: Understand child process communication
The parent sends 'Hello' to the child. The child responds with an object{ reply: 'Hi' }viaprocess.send().Step 2: Analyze parent's message event handler
The parent'schild.on('message')receives the object and logs it asParent got: { reply: 'Hi' }.Final Answer:
Parent got: { reply: 'Hi' } -> Option BQuick Check:
Child sends object, parent logs object [OK]
- Assuming string 'Hi' instead of object
- Expecting parent's message to be 'Hello'
- Confusing child and parent message directions
const { Worker } = require('worker_threads');
const worker = Worker('worker.js');Solution
Step 1: Check Worker thread creation syntax
TheWorkerclass must be instantiated with thenewkeyword.Step 2: Identify error in code
The code callsWorker('worker.js')withoutnew, causing a TypeError.Final Answer:
Missing new keyword before Worker constructor -> Option CQuick Check:
Usenew Worker()to create threads [OK]
- Forgetting new keyword
- Importing wrong module for threads
- Thinking worker.js must be JSON
Solution
Step 1: Understand CPU-heavy task impact
CPU-heavy tasks block the main event loop if run directly, causing app unresponsiveness.Step 2: Compare worker threads and child processes for heavy tasks
Worker threads share memory but still run in the same process, which can cause contention. Child processes run in separate processes, isolating CPU load and preventing blocking.Step 3: Evaluate other options
Running asynchronously in main thread or delaying with setTimeout does not prevent blocking for CPU-heavy tasks.Final Answer:
Use a child process to run the task in a separate process communicating via messages. -> Option AQuick Check:
Heavy CPU tasks best isolated in child processes [OK]
- Assuming worker threads fully isolate CPU load
- Thinking async or setTimeout avoids CPU blocking
- Ignoring message communication overhead
