Bird
0
0

What will be the output of this Node.js cluster code snippet?

medium📝 Predict Output Q5 of 15
Node.js - Cluster Module
What will be the output of this Node.js cluster code snippet?
const cluster = require('cluster');
if (cluster.isPrimary) {
  cluster.fork();
  cluster.fork();
  console.log('Number of workers:', Object.keys(cluster.workers).length);
} else {
  console.log('Worker PID:', process.pid);
}
ANumber of workers: 1 and 1 time 'Worker PID: <pid>'
BNumber of workers: 2 and 2 times 'Worker PID: <pid>'
CNumber of workers: 0 and 2 times 'Worker PID: <pid>'
DNumber of workers: 2 and 1 time 'Worker PID: <pid>'
Step-by-Step Solution
Solution:
  1. Step 1: Fork two workers

    cluster.fork() is called twice, creating 2 workers.
  2. Step 2: Master logs worker count, workers log their PID

    Master logs 'Number of workers: 2'. Each worker logs its PID once.
  3. Final Answer:

    Number of workers: 2 and 2 times 'Worker PID: <pid>' -> Option B
  4. Quick Check:

    Fork count matches worker logs [OK]
Quick Trick: Each fork creates one worker process [OK]
Common Mistakes:
  • Assuming only one worker is created
  • Confusing master and worker output counts
  • Ignoring Object.keys(cluster.workers).length

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Node.js Quizzes