cluster.isMaster
- Node.js course
- Advanced
- Lesson 4/83
- 5 min
Learn master/worker distinction with cluster.isMaster.
cluster.isMaster
cluster.isMaster returns true in the master process and false in a worker. This flag lets the same code tell whether it runs as master or worker.
A typical pattern: if (cluster.isMaster) { cluster.fork(); }. The master forks and returns; the worker starts the server. This prevents an infinite fork loop.
cluster.isWorker
cluster.isWorker is the inverse of cluster.isMaster: it returns true in a worker and false in the master. Sometimes isWorker reads more naturally.
For example: if (cluster.isWorker) { startServer(); }. Together the two flags make the execution context explicit.
Practice Log the isMaster value
Import the cluster module. Log cluster.isMaster with console.log.
Starter code
// Import the cluster module
// log the isMaster valueSample solution
const cluster = require("cluster");
console.log(cluster.isMaster);Expected output
true
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What does cluster.isMaster return in the master?
- false
- undefined
- null
- true Correct answer
Explanation: isMaster returns true in the master process.
2 Match each piece to its role
| Term | Meaning |
|---|---|
cluster.isMaster |
Main process? |
cluster.isWorker |
Worker? |
true |
Main process |
false |
Worker process |
3 Complete the flag name
if (cluster.____) { cluster.fork(); }
if (cluster.isMaster) { cluster.fork(); }
Explanation: cluster.isMaster returns true in the master.