Worker threads let you run code in the background without stopping your main program. This helps your app stay fast and smooth.
Creating worker threads 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', (msg) => { console.log('Message from worker:', msg); }); worker.postMessage('start');
The Worker class creates a new thread running a separate JavaScript file.
You communicate with the worker using postMessage and listen for messages with on('message').
worker.js.import { Worker } from 'worker_threads'; // Create a worker from a file const worker = new Worker('./worker.js');
worker.on('message', (msg) => { console.log('Received:', msg); });
worker.postMessage('Hello Worker');This example shows how to create a worker thread inside the same file. The main thread sends a message to the worker, and the worker replies back.
import { Worker, isMainThread, parentPort } from 'worker_threads'; if (isMainThread) { // This is the main thread const worker = new Worker(new URL(import.meta.url)); worker.on('message', (msg) => { console.log('Message from worker:', msg); }); worker.postMessage('Hello Worker'); } else { // This is the worker thread parentPort.on('message', (msg) => { // Respond back with a message parentPort.postMessage(`Worker received: ${msg}`); }); }
Worker threads run in separate memory, so you must send messages to share data.
Use isMainThread to check if code is running in the main or worker thread.
Worker threads help keep your app fast by doing heavy work in the background.
Worker threads let you run code in parallel without blocking your main program.
You create a worker with new Worker() and communicate using messages.
This helps your app stay responsive during heavy tasks.
Practice
worker_threads in Node.js?Solution
Step 1: Understand worker threads role
Worker threads allow running JavaScript code in parallel threads separate from the main thread.Step 2: Compare with other options
Options B, C, and D describe unrelated tasks; worker threads specifically help avoid blocking the main thread.Final Answer:
To run code in parallel without blocking the main thread -> Option DQuick Check:
Parallel code execution = A [OK]
- Confusing worker threads with async callbacks
- Thinking worker threads manage HTTP or DB tasks directly
worker_threads module?Solution
Step 1: Recall correct import syntax
The Worker class is a named export, so we use destructuring:const { Worker } = require('worker_threads');Step 2: Check other options
const Worker = require('worker_threads'); assigns the entire module object, not the Worker class. import Worker from 'worker_threads'; uses ES module syntax which requires extra config. const Worker = require('worker_threads').worker; uses wrong property name.Final Answer:
const { Worker } = require('worker_threads'); -> Option CQuick Check:
Destructure Worker from module = D [OK]
- Using wrong property name like 'worker' instead of 'Worker'
- Mixing CommonJS and ES module syntax incorrectly
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 and worker thread roles
Main thread creates a worker running the same file. It sends 'Hello' to worker.Step 2: Trace message passing
Worker receives 'Hello', appends ' World', and sends back 'Hello World'. Main thread logs this message.Final Answer:
From worker: Hello World -> Option AQuick Check:
Message sent + ' World' logged = B [OK]
- Expecting original message without modification
- Confusing main thread and worker thread roles
- Missing event listeners for messages
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 Worker constructor argument
The Worker constructor expects an absolute path or a URL, not just a relative string like 'worker.js'.Step 2: Validate other options
Cannot create Worker with a string filename is incorrect because Worker can be created with a filename if path is correct. Missing event listener for 'error' event is good practice but not an error. Cannot call postMessage on Worker instance is wrong; postMessage is valid on Worker.Final Answer:
Worker file path should be absolute or URL -> Option AQuick Check:
Worker needs absolute path or URL = C [OK]
- Using relative paths without resolving them
- Ignoring error event listeners
- Thinking postMessage is invalid on Worker
Solution
Step 1: Identify correct Worker creation and communication
Creating a worker withnew Worker('./calc.js')and usingworker.on('message')plusworker.postMessage()is the standard pattern.Step 2: Eliminate incorrect options
Usenew Worker()without arguments and callworker.send()to communicate is invalid because Worker requires a filename or code. Userequire('worker_threads').run()to start the worker and get a promise is incorrect; no run() method exists. Create a child process withchild_process.fork()and communicate withworker.postMessage()uses child_process, not worker_threads, and postMessage is not valid on child processes.Final Answer:
Use new Worker('./calc.js') with worker.on('message', callback) and send data via worker.postMessage() -> Option BQuick Check:
Worker with filename + message events = A [OK]
- Trying to create Worker without filename
- Confusing child_process with worker_threads
- Using non-existent Worker methods
