Bird
0
0

You want to write a function that reads a file and uses an error-first callback. Which of these correctly handles both error and data?

hard📝 Application Q8 of 15
Node.js - Error Handling Patterns
You want to write a function that reads a file and uses an error-first callback. Which of these correctly handles both error and data?
Afunction readFile(callback) { fs.readFile('file.txt', (err, data) => { callback(data, err); }); }
Bfunction readFile(callback) { fs.readFile('file.txt', (data, err) => { if (err) callback(err); else callback(null, data); }); }
Cfunction readFile(callback) { fs.readFile('file.txt', (err, data) => { if (err) callback(err); else callback(null, data); }); }
Dfunction readFile(callback) { fs.readFile('file.txt', (err, data) => { callback(data); }); }
Step-by-Step Solution
Solution:
  1. Step 1: Check parameter order in callback

    fs.readFile callback uses (err, data) order, so function readFile(callback) { fs.readFile('file.txt', (err, data) => { if (err) callback(err); else callback(null, data); }); } matches this.
  2. Step 2: Verify error handling and callback calls

    function readFile(callback) { fs.readFile('file.txt', (err, data) => { if (err) callback(err); else callback(null, data); }); } calls callback with error if present, else with null and data.
  3. Final Answer:

    function readFile(callback) { fs.readFile('file.txt', (err, data) => { if (err) callback(err); else callback(null, data); }); } -> Option C
  4. Quick Check:

    Correct error-first callback usage = function readFile(callback) { fs.readFile('file.txt', (err, data) => { if (err) callback(err); else callback(null, data); }); } [OK]
Quick Trick: Pass error first, then data in callback [OK]
Common Mistakes:
  • Swapping err and data parameters
  • Passing data as first argument
  • Ignoring error argument in callback

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Node.js Quizzes