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.
0
0
Receiving results from workers in Node.js
Introduction
When you want to do heavy calculations without freezing your app.
When you need to run multiple tasks at the same time and collect their results.
When you want to keep your app responsive while workers do background jobs.
When you want to split a big job into smaller parts and combine the results.
When you want to handle tasks like file processing or data fetching in parallel.
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
Listen for any message from the worker and print it.
Node.js
worker.on('message', (data) => { console.log('Got:', data); });
Send a task object to the worker to start processing.
Node.js
worker.postMessage({ task: 'calculate', numbers: [1, 2, 3] });Handle errors coming from the worker to avoid crashes.
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
});
}OutputSuccess
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.