Communicating via postMessage and 'message' Events
You'll learn: How to send data between the main thread and a Worker thread using postMessage() and the message event.
The Communication Bridge
Once you've created a Worker (in Node.js or the browser), you need a way to send instructions to it and receive results back. Think of it like passing notes through a wall—you can't reach through directly, but you can slide messages under the door in both directions.
The postMessage() method sends data to the worker, while the message event listener lets you receive data from the worker. This works bidirectionally: both the main thread and the worker can send and receive.
Sending Data to a Worker
From the main thread, call postMessage() on the worker instance:
const { Worker } = require('worker_threads');
const worker = new Worker('./my-worker.js');
worker.postMessage({ task: 'calculate', value: 42 });
Receiving Data in the Worker
Inside the worker script, listen for the message event using parentPort:
const { parentPort } = require('worker_threads');
parentPort.on('message', (data) => {
console.log('Worker received:', data);
// Process and respond
parentPort.postMessage({ result: data.value * 2 });
});
Receiving Responses in Main Thread
Back in the main thread, listen for responses from the worker:
worker.on('message', (response) => {
console.log('Main thread received:', response);
// { result: 84 }
});
The pattern is symmetrical: both sides use postMessage() to send and message events to receive. Data is serialized (copied) when passed, ensuring thread safety.
Key Takeaway: Use postMessage() to send data to a worker and listen for message events to receive data back—this bidirectional communication pattern works identically from both the main thread and worker thread.