How to pass messages between threads with web workers in JS

Web workers are used in JavaScript to transmit messages between threads. JavaScript code can be run using web workers, which are independent of the main UI thread and use message passing to interact with it.

Here's a demonstration of how to use web workers for passing messages between threads:

  1. Create a new web worker:

// main.js
const worker = new Worker('worker.js');
  1. Add an event listener to receive messages from the web worker:

worker.on('message', (message) => {
console.log('Message received from worker:', message);
});
  1. Send a message to the web worker:

// Send a message to the worker
worker.postMessage('Hello from the main thread!');
  1. Handle messages in the web worker:

// worker.js
const { parentPort } = require('worker_threads');
// Receive messages from the main thread
parentPort.on('message', (message) => {
console.log('Message received from main thread:', message);
// Send a message back to the main thread
parentPort.postMessage('Hello from the worker thread!');
});

In line 1: We import the parentPort object from the Node.js built-in module worker_threads. The parentPort is a communication channel that allows the worker thread to communicate with the main thread.

In line 5: Here, an event listener is set up on the parentPort object. It listens for messages sent from the main thread.

In line 6: When a message is received from the main thread, this line logs the received message along with a message indicating that it was received.

In line 9: After receiving a message from the main thread, this line sends a response message back to the main thread using the postMessage method of the parentPort object. In this case, it sends the message "Hello from the worker thread!" back to the main thread.

By following this pattern, we can pass messages back and forth between the main thread and a web worker in JavaScript.

Code Example:

The following is a code example that passes messages between threads:

const { parentPort } = require('worker_threads');

// Receive messages from the main thread
parentPort.on('message', (message) => {
  console.log('Message received from main thread:', message);

  // Send a message back to the main thread
  parentPort.postMessage('Hello from the worker thread!');
});
Messages passing between threads

After running the example above, we’ll get the first message from the main thread, followed by the message from the worker thread.

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved