Bird
0
0

How can you modify this code to capture both stdout and stderr output into a single string variable?

hard📝 Application Q9 of 15
Node.js - Child Processes
How can you modify this code to capture both stdout and stderr output into a single string variable?
const { spawn } = require('child_process');
const proc = spawn('grep', ['pattern', 'file.txt']);
let output = '';
proc.stdout.on('data', data => output += data.toString());
proc.stderr.on('data', data => console.error(data.toString()));
AUse <code>proc.stdin.on('data')</code> instead
BReplace stdout listener with stderr listener
CAdd <code>proc.stderr.on('data', data => output += data.toString());</code>
DSpawn with option { mergeStreams: true }
Step-by-Step Solution
Solution:
  1. Step 1: Understand current output capture

    Currently only stdout data is appended to output.

  2. Step 2: Append stderr data to same variable

    Listen to stderr 'data' event and append its data to output as well.

  3. Final Answer:

    Add proc.stderr.on('data', data => output += data.toString()); -> Option C
  4. Quick Check:

    Append both stdout and stderr data to variable [OK]
Quick Trick: Listen to both stdout and stderr 'data' events to combine output [OK]
Common Mistakes:
  • Ignoring stderr output
  • Replacing stdout listener instead of adding
  • Using stdin instead of stderr

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Node.js Quizzes