Bird
0
0

Identify the error in this code snippet that tries to restart a worker after it crashes:

medium📝 Debug Q14 of 15
Node.js - Cluster Module
Identify the error in this code snippet that tries to restart a worker after it crashes:
const cluster = require('cluster');
if (cluster.isMaster) {
  cluster.fork();
  cluster.on('exit', (worker) => {
    console.log('Worker crashed, restarting...');
    cluster.fork();
  });
}
AThe 'exit' event should be listened on 'cluster' but the callback parameter should be (worker, code, signal)
BThe 'exit' event should be listened on 'cluster.workers', not 'cluster'
CThe 'exit' event should be listened on 'cluster' but the callback parameters are wrong
DThe 'exit' event callback parameters are incorrect; it should receive (code, signal)
Step-by-Step Solution
Solution:
  1. Step 1: Check where to listen for worker exit

    The 'exit' event is emitted by the cluster module, and the callback receives (worker, code, signal).
  2. Step 2: Identify callback parameter mismatch

    The code uses only one parameter (worker), but the event provides three parameters; this can cause confusion or errors.
  3. Final Answer:

    The 'exit' event should be listened on 'cluster' but the callback parameter should be (worker, code, signal) -> Option A
  4. Quick Check:

    cluster.on('exit', (worker, code, signal)) is correct [OK]
Quick Trick: cluster.on('exit') callback needs (worker, code, signal) parameters [OK]
Common Mistakes:
  • Listening on cluster.workers instead of cluster
  • Using wrong callback parameters
  • Ignoring code and signal parameters

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Node.js Quizzes