Workers help run tasks in the background without stopping your main program. Receiving results from workers lets you get the answers or data they finish.
Receiving results from workers in Node.js
Start learning this pattern below
Jump into concepts and practice - no test required
or
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Introduction
Syntax
Node.js
const { Worker } = require('worker_threads');
const worker = new Worker('./worker.js');
worker.on('message', (result) => {
console.log('Result from worker:', result);
});
worker.postMessage('start');The message event listens for results sent from the worker.
Use postMessage to send data or commands to the worker.
Examples
Node.js
worker.on('message', (data) => { console.log('Got:', data); });
Node.js
worker.postMessage({ task: 'calculate', numbers: [1, 2, 3] });Node.js
worker.on('error', (err) => { console.error('Worker error:', err); });
Sample Program
This program creates a worker that calculates the square of a number sent from the main thread. The main thread sends the number 10, and the worker sends back 100.
Node.js
const { Worker, isMainThread, parentPort } = require('worker_threads');
if (isMainThread) {
// Main thread code
const worker = new Worker(__filename);
worker.on('message', (result) => {
console.log('Result from worker:', result);
});
worker.on('error', (err) => {
console.error('Worker error:', err);
});
worker.postMessage(10); // Send number to worker
} else {
// Worker thread code
parentPort.on('message', (num) => {
// Calculate square
const square = num * num;
parentPort.postMessage(square); // Send result back
});
}Important Notes
Always listen for the error event on workers to catch problems.
Workers communicate only by sending messages; you cannot share variables directly.
Use isMainThread to separate main and worker code in the same file.
Summary
Workers run tasks in the background to keep your app smooth.
You receive results by listening to the message event from the worker.
Send data to workers using postMessage and handle errors properly.
Practice
1. In Node.js, how do you receive results from a worker thread?
easy
Solution
Step 1: Understand worker communication
Workers send results back to the main thread using messages.Step 2: Use the correct event listener
The main thread listens to themessageevent on the worker to receive data.Final Answer:
By listening to themessageevent on the worker -> Option CQuick Check:
message event = D [OK]
Hint: Remember: workers send data via 'message' events [OK]
Common Mistakes:
- Trying to call a non-existent method like getResult()
- Expecting console.log output to be received
- Reading results from files instead of messages
2. Which of the following is the correct syntax to listen for messages from a worker in Node.js?
easy
Solution
Step 1: Recall Node.js worker event syntax
Node.js workers use theonmethod to listen for events.Step 2: Identify the correct event and method
The event to receive data ismessage, and the syntax isworker.on('message', callback).Final Answer:
worker.on('message', (result) => { console.log(result); }); -> Option AQuick Check:
worker.on('message') = A [OK]
Hint: Use worker.on('message', callback) to get results [OK]
Common Mistakes:
- Using non-existent methods like listen or receive
- Confusing browser event syntax with Node.js
- Using addEventListener which is not in Node.js workers
3. What will be logged to the console when this Node.js worker code runs?
const { Worker } = require('worker_threads');
const worker = new Worker(`
const { parentPort } = require('worker_threads');
parentPort.postMessage('Hello from worker');
`, { eval: true });
worker.on('message', (msg) => console.log(msg));medium
Solution
Step 1: Understand worker code execution
The worker sends a message 'Hello from worker' usingparentPort.postMessage.Step 2: Check main thread message listener
The main thread listens to themessageevent and logs the received message.Final Answer:
Hello from worker -> Option DQuick Check:
postMessage sends 'Hello from worker' = B [OK]
Hint: postMessage sends data, main thread logs it on 'message' event [OK]
Common Mistakes:
- Expecting no output because of missing event listener
- Confusing parentPort usage causing errors
- Assuming worker code runs in main thread
4. Identify the error in this Node.js worker communication code:
const { Worker } = require('worker_threads');
const worker = new Worker('./worker.js');
worker.on('message', (data) => {
console.log('Received:', data);
});
parentPort.postMessage('start');medium
Solution
Step 1: Understand where postMessage is called
In Node.js,postMessageis called onparentPortinside the worker, not on the worker instance in main thread.Step 2: Identify correct communication method
The main thread usesworker.postMessage()to send messages to the worker, but inside the worker,parentPort.postMessage()sends messages back.Final Answer:
postMessage should be called on parentPort inside worker, not on worker instance -> Option BQuick Check:
postMessage usage inside worker = C [OK]
Hint: postMessage on worker sends to worker; inside worker use parentPort.postMessage [OK]
Common Mistakes:
- Confusing where to call postMessage
- Ignoring error event listeners
- Assuming worker file path is wrong without evidence
5. You want to receive multiple results from a worker that sends messages repeatedly. Which approach correctly handles this in Node.js?
const { Worker } = require('worker_threads');
const worker = new Worker('./worker.js');
// What should you do here to receive all messages?hard
Solution
Step 1: Understand event listeners for multiple messages
Usingworker.on('message')listens continuously for all messages sent by the worker.Step 2: Compare with other options
oncelistens only once, loops or polling are unnecessary and inefficient for receiving messages.Final Answer:
Use worker.on('message', (msg) => { console.log(msg); }); to listen continuously -> Option AQuick Check:
Continuous message listening = A [OK]
Hint: Use worker.on('message') for all messages, not once or polling [OK]
Common Mistakes:
- Using once instead of on for multiple messages
- Trying to poll worker instead of event listening
- Confusing sending messages with receiving them
