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 master
process to the worker
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 forked worker.
if (cluster.isMaster) {
// This block of code is where the master process lives
// fork a single worker
const worker = cluster.fork();
// send a messsage from master process
// to the wroker process
worker.send({ data: "Hi Worker!" });
} else {
// This block of code is where worker process lives
}
Now to receive the message in the worker
process, we have to listen for any messages from the master
process.
This can be done using the message
event on the process
object like this,
if (cluster.isMaster) {
// This block of code is where the master process lives
// fork a single worker
const worker = cluster.fork();
// send a messsage from master process
// to the wroker process
worker.send({ data: "Hi Worker!" });
} else {
// This block of code is where the worker process lives
process.on("message", (msg) => {});
}
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();
// send a messsage from master process
// to the wroker process
worker.send({ data: "Hi Worker!" });
} else {
// This block of code is where the worker process lives
process.on("message", (msg) => {
// check for data property
// on msg object
if (msg.data) {
console.log(`Message received to worker from master: ${msg.data}`);
}
});
}
We have successfully passed our message from the master
process to the worker
process 🔥.