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.
const fs = require('fs');
fs.readFile('data.txt', 'utf8', (err, data) => {
if (err) {
console.error('Error:', err.message);
return;
}
console.log(data);
});Error: ENOENT: no such file or directoryThe first callback argument (err) is checked before using the result.
function fetchData(cb) {
setTimeout(() => cb(null, { id: 1 }), 500);
}
fetchData((err, data) => {
if (err) return console.error(err);
console.log(data);
});{ 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.
