Common Error-First APIs in Node.js
You'll learn which core Node.js modules follow the error-first callback pattern and how to use them safely.
The Pattern in Action
Now that you understand error-first callbacks, it's time to see them in the wild. Node.js core modules heavily rely on this pattern, making it essential to recognize and handle correctly.
File System Operations
The fs module is where you'll encounter error-first callbacks most frequently:
const fs = require('fs');
// Reading a file
fs.readFile('data.txt', 'utf8', (err, data) => {
if (err) {
console.error('Failed to read file:', err.message);
return;
}
console.log('File contents:', data);
});
// Writing a file
fs.writeFile('output.txt', 'Hello!', (err) => {
if (err) {
console.error('Failed to write file:', err.message);
return;
}
console.log('File written successfully');
});
Other Common Examples
Many Node.js APIs follow this same convention:
const fs = require('fs');
const crypto = require('crypto');
// Checking file stats
fs.stat('myfile.txt', (err, stats) => {
if (err) {
console.error('File does not exist');
return;
}
console.log('File size:', stats.size);
});
// Generating random bytes
crypto.randomBytes(16, (err, buffer) => {
if (err) {
console.error('Random generation failed:', err.message);
return;
}
console.log('Random hex:', buffer.toString('hex'));
});
The Consistent Pattern
Notice the consistency: error first, data second. This convention makes Node.js code predictable. You always check err before accessing your result, preventing crashes from undefined data.
Key Takeaway: Node.js core modules like fs, crypto, and others standardize on error-first callbacks—always check the error parameter before using the result to write robust asynchronous code.