Bird
0
0

You spawn a child process in Node.js that may exit with code 7 or be terminated by a signal. Which code snippet correctly logs the exit code or the signal name?

hard📝 Application Q8 of 15
Node.js - Child Processes
You spawn a child process in Node.js that may exit with code 7 or be terminated by a signal. Which code snippet correctly logs the exit code or the signal name?
const { spawn } = require('child_process');
const child = spawn('node', ['-e', 'process.exit(7)']);
child.on('exit', (code, signal) => {
  // What to log?
});
Achild.on('exit', (code, signal) => { console.log(signal || code); });
Bchild.on('exit', (code, signal) => { console.log(code || signal); });
Cchild.on('exit', (code) => { console.log(code); });
Dchild.on('exit', (signal) => { console.log(signal); });
Step-by-Step Solution
Solution:
  1. Step 1: Understand exit event parameters

    The 'exit' event provides code (number) and signal (string or null).
  2. Step 2: Determine which to log

    If the process was terminated by a signal, signal is non-null; otherwise, code holds the exit code.
  3. Step 3: Correct logging logic

    Logging signal || code ensures signal name is logged if present, else exit code.
  4. Final Answer:

    Option A correctly logs the signal or exit code. -> Option A
  5. Quick Check:

    Signal takes precedence over exit code [OK]
Quick Trick: Log signal if present, else exit code [OK]
Common Mistakes:
  • Logging code before checking signal
  • Ignoring signal parameter
  • Using only one parameter in listener

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Node.js Quizzes