Node.js ยท Chapter 32 of 43

Error-First Callbacks

Before Promises and async/await, Node.js established a convention called 'error-first callbacks': the first argument to a callback is always an error (or null), followed by the result.

Many built-in Node.js APIs (like fs.readFile) still use this pattern.

The pattern

A callback function looks like `(err, result) => { ... }`. You must always check if `err` is truthy before using `result`.

Why it matters

This consistent convention lets developers immediately know how to check for and handle failures across all of Node's built-in async APIs.

Example 1 (javascript)
const fs = require('fs');
fs.readFile('data.txt', 'utf8', (err, data) => {
  if (err) {
    console.error('Error:', err.message);
    return;
  }
  console.log(data);
});
Output
Error: ENOENT: no such file or directory

The first callback argument (err) is checked before using the result.

Example 2 (javascript)
function fetchData(cb) {
  setTimeout(() => cb(null, { id: 1 }), 500);
}
fetchData((err, data) => {
  if (err) return console.error(err);
  console.log(data);
});
Output
{ id: 1 }

A successful call passes null as the error and the real result second.

Key points

  • Error-first callbacks put an error/null as the first argument.
  • Always check `if (err)` before using the result.
  • Many core Node.js APIs still follow this convention.
  • Modern code often wraps these in Promises for use with async/await.
๐Ÿ’ก Note: Node's `util.promisify()` can convert error-first callback functions into Promise-based ones.

๐Ÿ“ Quick Quiz

1. In an error-first callback, what is the first parameter?

2. What should you always do before using the result argument?

3. What utility converts callback functions to Promise-based ones?