Loading lessons...
Asynchronous File System (fs & fs/promises)
Reading and Writing Files
The built-in fs module allows Node.js applications to interact with the file system. It provides synchronous methods, callback-based methods, and modern Promise-based APIs.
Callback vs Promises API
Avoid synchronous methods (fs.readFileSync) in production servers because they block the single main execution thread!
// Recommended: fs/promises with async/await
const fs = require("node:fs/promises");
const path = require("node:path");
async function processConfigFile() {
const filePath = path.join(__dirname, "config.json");
try {
// Write JSON file
const data = { env: "production", port: 5000 };
await fs.writeFile(filePath, JSON.stringify(data, null, 2), "utf-8");
// Read JSON file back
const content = await fs.readFile(filePath, "utf-8");
const parsed = JSON.parse(content);
console.log("Config loaded:", parsed.port);
// Check file existence
await fs.access(filePath);
console.log("File exists!");
} catch (err) {
console.error("File I/O Error:", err.message);
}
}
processConfigFile();
Common File System Operations
fs.readFile(path, encoding): Reads entire file contents.fs.writeFile(path, data): Writes data to file (overwrites existing).fs.appendFile(path, data): Appends data to end of file.fs.mkdir(path, { recursive: true }): Creates directory (including parent folders if needed).fs.unlink(path): Deletes a file.
TL;DR
- Always prefer
fs/promiseswithasync/awaitover sync methods in backend applications. - Specify encoding (e.g.
'utf-8') when reading files as strings.