Worker IPC
- Node.js course
- Advanced
- Lesson 3/83
- 5 min
Learn inter-worker communication with IPC.
Worker IPC
Worker processes do not share memory; so master-worker communication uses IPC (Inter-Process Communication). IPC is a built-in messaging channel provided by the cluster module.
The master sends messages with worker.send(msg) and catches worker messages with cluster.on("message"). On the worker side you use process.send(msg) and process.on("message"). Messages must be plain objects.
The message event
In the cluster module the "message" event fires on the master when a worker sends a message. The handler takes two parameters: worker (the sender) and msg (the content).
This pattern is ideal for workers that finish long calculations and report back. For example, a worker prepares a report and calls process.send({ done: true }) to notify the master.
Practice Register a message handler
Register a "message" event handler on cluster. Then log "IPC ready".
Starter code
// Import the cluster module
// listen for the message event
// log "IPC ready"Sample solution
const cluster = require("cluster");
cluster.on("message", (worker, msg) => {});
console.log("IPC ready");Expected output
IPC ready
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Match each piece to its role
| Term | Meaning |
|---|---|
worker.send |
Sends to worker |
process.send |
Sends to parent |
message event |
Catches message |
IPC |
Inter-process communication |
2 Complete the event name
cluster.on("____", (worker, msg) => {})
cluster.on("message", (worker, msg) => {})
Explanation: The message event catches worker messages.
3 Which event fires when a worker sends a message?
- exit
- online
- message Correct answer
- listening
Explanation: The message event fires when a worker sends a message.