Bird
0
0

Consider this code snippet:

medium📝 component behavior Q13 of 15
Node.js - Child Processes
Consider this code snippet:
const { spawn } = require('child_process');
const ls = spawn('ls', ['-l']);
ls.stdout.on('data', (data) => {
  console.log(`Output: ${data}`);
});
ls.stderr.on('data', (data) => {
  console.error(`Error: ${data}`);
});
ls.on('close', (code) => {
  console.log(`Process exited with code ${code}`);
});
What will this code do when run in a directory?
APrint the detailed list of files, errors if any, and exit code when done.
BOnly print errors and ignore normal output.
CBuffer all output and print it after the process ends.
DThrow a syntax error because of wrong event names.
Step-by-Step Solution
Solution:
  1. Step 1: Analyze event listeners

    The code listens to stdout data events to print output live, stderr for errors, and close to know when the process ends.
  2. Step 2: Understand spawn behavior

    spawn streams output, so the console logs will show file list lines as they come, errors if any, and finally the exit code.
  3. Final Answer:

    Print the detailed list of files, errors if any, and exit code when done. -> Option A
  4. Quick Check:

    spawn streams output and errors live = D [OK]
Quick Trick: spawn streams stdout, stderr, and close events [OK]
Common Mistakes:
  • Thinking output is buffered until process ends
  • Ignoring stderr event handling
  • Assuming event names are incorrect

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Node.js Quizzes