Topic 34 of 55
File (fs) Asynchronous Callbacks
Overview
To prevent blocking the event loop, the traditional `fs` methods use asynchronous callbacks. Node.js initiates the file read, moves on to other code, and then runs the callback function when the file is ready. This is non-blocking.
Syntax
javascript
const fs = require('fs');
// Note: No 'Sync' suffix.
// The last argument is a callback function following the "Error-First" pattern.
fs.readFile('./data.txt', 'utf8', (err, data) => {
// Parameter 1: Error object (null if successful)
if (err) {
console.error("Error reading file:", err);
return; // Exit the callback early
}
// Parameter 2: The actual data
console.log("File content:", data);
});
console.log("This will print BEFORE the file content!");Common Pitfalls
- Always check for the `err` object first inside a callback. If you try to use `data` when `err` exists, your app will crash because `data` will be undefined.
- Deeply nested callbacks are hard to read and maintain. This pattern is largely obsolete in modern Node.js in favor of Promises (`fs/promises`).
Real-World Example
The dreaded 'Callback Hell' (Pyramid of Doom) when doing multiple async operations:
example
javascript
const fs = require('fs');
// Reading a file, transforming it, and writing to a new file
fs.readFile('./input.txt', 'utf8', (err, data) => {
if (err) return console.error(err);
const modified = data.toUpperCase();
fs.writeFile('./output.txt', modified, (err) => {
if (err) return console.error(err);
fs.appendFile('./log.txt', 'File modified', (err) => {
if (err) return console.error(err);
console.log("All operations completed.");
});
});
});