Worker threads let Node.js do many things at once without slowing down. They help run heavy tasks separately so your app stays fast and smooth.
Why worker threads matter in Node.js
Start learning this pattern below
Jump into concepts and practice - no test required
import { Worker } from 'worker_threads'; const worker = new Worker('./worker.js'); worker.on('message', (result) => { console.log('Result from worker:', result); }); worker.postMessage('start');
The Worker class creates a new thread running a separate file.
You communicate with the worker using postMessage and listen for messages with on('message').
import { Worker } from 'worker_threads'; const worker = new Worker('./worker.js'); worker.on('message', (msg) => { console.log('Message from worker:', msg); }); worker.postMessage('Hello Worker');
import { Worker } from 'worker_threads'; const worker = new Worker(` const { parentPort } = require('worker_threads'); parentPort.on('message', (msg) => { parentPort.postMessage(msg.toUpperCase()); }); `, { eval: true }); worker.on('message', (msg) => { console.log('Uppercase:', msg); }); worker.postMessage('hello');
This program calculates the 10th Fibonacci number in a worker thread. It keeps the main app free to do other things while the calculation runs.
import { Worker } from 'worker_threads'; function runWorker() { return new Promise((resolve, reject) => { const worker = new Worker(` const { parentPort } = require('worker_threads'); function fibonacci(n) { if (n <= 1) return n; return fibonacci(n - 1) + fibonacci(n - 2); } parentPort.on('message', (num) => { const result = fibonacci(num); parentPort.postMessage(result); }); `, { eval: true }); worker.on('message', resolve); worker.on('error', reject); worker.postMessage(10); }); } (async () => { const result = await runWorker(); console.log('Fibonacci of 10 is', result); })();
Worker threads run in separate memory, so you must send data back and forth using messages.
Use worker threads for CPU-heavy tasks, not for simple I/O operations.
Remember to handle errors from workers to avoid crashes.
Worker threads help Node.js run heavy tasks without freezing the app.
They let you use multiple CPU cores by running code in parallel.
You communicate with workers using messages to keep your app responsive.
Practice
Solution
Step 1: Understand the main thread limitation
Node.js runs JavaScript on a single main thread, so heavy tasks can block it and freeze the app.Step 2: Role of worker threads
Worker threads run heavy tasks in parallel, keeping the main thread free and the app responsive.Final Answer:
They allow running heavy tasks without freezing the main app. -> Option AQuick Check:
Worker threads keep app responsive = B [OK]
- Thinking worker threads replace async programming
- Believing worker threads reduce memory automatically
- Assuming worker threads fix bugs
Solution
Step 1: Recall the Worker class usage
Node.js uses the Worker class from 'worker_threads' module to create worker threads.Step 2: Correct syntax
The correct syntax is creating a new Worker instance with the file path as argument.Final Answer:
const worker = new Worker('./worker.js'); -> Option DQuick Check:
Use new Worker() to create worker thread = D [OK]
- Using Worker.create() which does not exist
- Using Thread instead of Worker
- Calling createWorker() which is not a Node.js method
const { Worker, isMainThread, parentPort } = require('worker_threads');
if (isMainThread) {
const worker = new Worker(__filename);
worker.on('message', msg => console.log('From worker:', msg));
worker.postMessage('Hello');
} else {
parentPort.on('message', msg => {
parentPort.postMessage(msg + ' World');
});
}Solution
Step 1: Understand main vs worker thread
The main thread creates a worker running the same file. It sends 'Hello' to the worker.Step 2: Worker message handling
The worker listens for messages, appends ' World' to the received message, and sends it back.Final Answer:
From worker: Hello World -> Option CQuick Check:
Worker appends ' World' and sends back = A [OK]
- Confusing main thread and worker thread roles
- Missing parentPort import causing errors
- Assuming no output without understanding message events
const { Worker } = require('worker_threads');
const worker = new Worker('./worker.js');
worker.on('message', (msg) => console.log(msg));
worker.postMessage('Start');Solution
Step 1: Check main thread code
Main thread creates worker and sends message correctly.Step 2: Common worker.js mistake
Inside worker.js, parentPort must be imported to receive and send messages.Final Answer:
Missing import of parentPort in worker.js -> Option BQuick Check:
Worker needs parentPort import to communicate = C [OK]
- Thinking postMessage is invalid on worker instance
- Believing file path must be absolute always
- Using 'onmessage' instead of 'message' event
Solution
Step 1: Understand CPU-heavy task impact
CPU-heavy tasks block the main thread if run there, freezing the app.Step 2: Worker threads for parallelism
Creating worker threads for each calculation runs them in parallel without blocking the main thread, communicating results via messages.Step 3: Evaluate other options
Async/await does not prevent blocking for CPU tasks; setTimeout only delays but does not parallelize; child processes are heavier and more complex than worker threads.Final Answer:
Create a worker thread for each calculation and communicate results via messages. -> Option AQuick Check:
Use worker threads for parallel CPU tasks = A [OK]
- Thinking async/await avoids CPU blocking
- Using setTimeout to fix blocking issues
- Confusing child processes with worker threads
