Bird
0
0

Identify the issue in this Node.js cluster code snippet:

medium📝 Debug Q7 of 15
Node.js - Cluster Module
Identify the issue in this Node.js cluster code snippet:
const cluster = require('cluster');
const os = require('os');
if (cluster.isPrimary) {
  for (let i = 0; i <= os.cpus().length; i++) {
    cluster.fork();
  }
}
AThe cluster module is not imported correctly
BThe loop condition uses '<=' causing one extra worker to be forked
Cos.cpus() returns a number, not an array
Dcluster.isPrimary should be cluster.isMaster
Step-by-Step Solution
Solution:
  1. Step 1: Check loop boundary

    The loop runs from 0 to os.cpus().length inclusive, which is one too many iterations.
  2. Step 2: Understand os.cpus()

    os.cpus() returns an array of CPU core info, so length is the number of cores.
  3. Step 3: Correct loop condition

    Use '<' instead of '<=' to avoid forking an extra worker.
  4. Final Answer:

    The loop condition uses '<=' causing one extra worker to be forked -> Option B
  5. Quick Check:

    Loop should run less than length [OK]
Quick Trick: Use '<' not '<=' in loops over array length [OK]
Common Mistakes:
  • Using '<=' instead of '<' in loop condition
  • Confusing cluster.isPrimary with cluster.isMaster (deprecated)
  • Misunderstanding os.cpus() return type

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Node.js Quizzes