Bird
0
0

Find the bug in this Node.js cluster code:

medium📝 Debug Q7 of 15
Node.js - Cluster Module
Find the bug in this Node.js cluster code:
const cluster = require('cluster');
if (cluster.isPrimary) {
  for (let i = 0; i <= 4; i++) {
    cluster.fork();
  }
  console.log('Workers:', Object.keys(cluster.workers).length);
} else {
  console.log('Worker started');
}
ALoop runs 5 times, but only 4 CPU cores exist, causing overhead.
Bcluster.fork() must be called asynchronously.
CNo bug; code runs fine regardless of CPU cores.
DUsing '<=' causes one extra worker beyond CPU cores.
Step-by-Step Solution
Solution:
  1. Step 1: Analyze loop condition

    The loop runs from 0 to 4 inclusive, totaling 5 iterations.
  2. Step 2: Compare with CPU cores

    Forking 5 workers may exceed CPU cores, causing inefficiency.
  3. Final Answer:

    Using '<=' causes one extra worker beyond CPU cores. -> Option D
  4. Quick Check:

    Use '<' to match CPU core count [OK]
Quick Trick: Use '<' not '<=' to match CPU cores in loops [OK]
Common Mistakes:
  • Ignoring loop boundary off-by-one error
  • Assuming extra workers improve performance
  • Thinking cluster.fork() needs async call

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Node.js Quizzes