How to send a message from the cluster worker process to the master process in Node.js?

November 1, 2020 - 3 min read

This blog is related to a previous blog called How to run the Node.js server on every CPU core?. Go check that out first if you want to learn more about the Master and Worker process.

To send a message from a cluster worker process to the master process, you can use the send() method on the worker process object.

Let's say we forked a worker process like this,

if (cluster.isMaster) {
  // This block of code is where the master process lives

  // fork a single worker
  const worker = cluster.fork();
} else {
  // This block of code is where worker process lives
}

Now let's use the send() method to send a message to the master process object (i.e process object is used to send messages to the master process).

if (cluster.isMaster) {
  // This block of code is where the master process lives

  // fork a single worker
  const worker = cluster.fork();
} else {
  // This block of code is where worker process lives

  // send a mesasge to master process
  // from worker process
  process.send({ data: "Hi Master!" });
}

Now to receive the message in the master process, we have to listen for any messages from the worker process.

This can be done by listening on the message event on the worker object like this,

if (cluster.isMaster) {
  // This block of code is where the master process lives

  // fork a single worker
  const worker = cluster.fork();

  // listen for any message from any worker process
  worker.on("message", (msg) => {});
} else {
  // This block of code is where worker process lives

  // send a mesasge to master process
  // from worker process
  process.send({ data: "Hi Master!" });
}

Inside the msg object, you can check for the data property where the message is located.

if (cluster.isMaster) {
  // This block of code is where the master process lives

  // fork a single worker
  const worker = cluster.fork();

  // listen for any message from any worker process
  worker.on("message", (msg) => {
    // check for data property
    // on msg object
    if (msg.data) {
      console.log(`Message received to master from worker: ${msg.data}`);
    }
  });
} else {
  // This block of code is where worker process lives

  // send a mesasge to master process
  // from worker process
  process.send({ data: "Hi Master!" });
}

We have successfully passed our message from the worker process to the master process 🔥.

Feel free to share if you found this useful 😃.