Bird
0
0

What will the following Node.js code output if the current directory contains a file named test.txt?

medium📝 component behavior Q13 of 15
Node.js - Child Processes
What will the following Node.js code output if the current directory contains a file named test.txt?
const { exec } = require('child_process');
exec('ls', (error, stdout, stderr) => {
  if (error) {
    console.error(`Error: ${error.message}`);
    return;
  }
  if (stderr) {
    console.error(`Stderr: ${stderr}`);
    return;
  }
  console.log(`Output: ${stdout}`);
});
AOutput: test.txt
BError: ls command not found
CStderr: Permission denied
DNo output
Step-by-Step Solution
Solution:
  1. Step 1: Understand exec running 'ls'

    The command ls lists files in the current directory. If test.txt exists, it will appear in the output.
  2. Step 2: Analyze callback behavior

    No error or stderr means output is printed with file names, so console logs 'Output: test.txt\n'.
  3. Final Answer:

    Output: test.txt -> Option A
  4. Quick Check:

    exec runs ls, outputs files = A [OK]
Quick Trick: exec callback logs stdout if no error or stderr [OK]
Common Mistakes:
  • Assuming error if command runs successfully
  • Ignoring stdout content
  • Confusing stderr with stdout

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Node.js Quizzes