Callback Hell Example: File Operations
You'll learn how reading multiple files one after another with Node.js callbacks creates deeply nested, hard-to-maintain code.
The Real-World Scenario
Imagine you need to read three configuration files in sequence: first a database config, then use info from it to read a server config, and finally read an app config based on both. With error-first callbacks, each file read depends on the previous one completing successfully.
Here's what callback hell looks like in practice:
const fs = require('fs');
// Reading three files sequentially
fs.readFile('db-config.json', 'utf8', (err, dbData) => {
if (err) {
console.error('Failed to read DB config:', err);
return;
}
// Parse first file, then read second
const dbConfig = JSON.parse(dbData);
fs.readFile('server-config.json', 'utf8', (err, serverData) => {
if (err) {
console.error('Failed to read server config:', err);
return;
}
const serverConfig = JSON.parse(serverData);
// Finally read third file
fs.readFile('app-config.json', 'utf8', (err, appData) => {
if (err) {
console.error('Failed to read app config:', err);
return;
}
const appConfig = JSON.parse(appData);
// Only now can we use all three configs
console.log('All configs loaded:', {
db: dbConfig,
server: serverConfig,
app: appConfig
});
});
});
});
Why This Is Problematic
Notice the rightward drift—each file operation nests one level deeper. Error handling repeats three times. If you needed to add a fourth file, you'd nest even further. The logic becomes difficult to follow, and modifying the sequence requires careful attention to braces and error paths.
Key Takeaway: Sequential file operations with callbacks create pyramid-shaped code that's hard to read, maintain, and extend—a classic example of callback hell in Node.js applications.