You are viewing a free preview of this lesson.
Subscribe to unlock all 10 lessons in this course and every other course on LearningBro.
One of Node.js's most powerful features is direct access to the file system. The built-in fs module provides functions for reading, writing, updating, deleting, and watching files and directories.
const fs = require("fs");
Node.js provides both asynchronous and synchronous versions of most fs operations. The async version is preferred in production because it does not block the event loop.
// Asynchronous read (non-blocking)
fs.readFile("notes.txt", "utf8", function (err, data) {
if (err) {
console.error("Error reading file:", err.message);
return;
}
console.log(data);
});
// Synchronous read (blocking — avoid in servers)
const data = fs.readFileSync("notes.txt", "utf8");
console.log(data);
Always pass "utf8" (or another encoding) as the second argument when you want a string. Without it you get a raw Buffer object.
// Overwrite or create the file
fs.writeFile("output.txt", "Hello, world!", "utf8", function (err) {
if (err) throw err;
console.log("File written successfully");
});
// Append to an existing file
fs.appendFile("log.txt", "New log entry\n", "utf8", function (err) {
if (err) throw err;
});
fs.access("config.json", fs.constants.F_OK, function (err) {
if (err) {
console.log("File does not exist");
} else {
console.log("File exists");
}
});
// Create a directory
fs.mkdir("uploads", { recursive: true }, function (err) {
if (err) throw err;
console.log("Directory created");
});
// List directory contents
fs.readdir(".", function (err, files) {
if (err) throw err;
files.forEach(function (file) {
console.log(file);
});
});
Since Node.js 10 the fs/promises module provides a Promise-based API that works cleanly with async/await:
const fs = require("fs/promises");
async function readConfig() {
try {
const data = await fs.readFile("config.json", "utf8");
return JSON.parse(data);
} catch (err) {
console.error("Could not read config:", err.message);
return {};
}
}
readConfig().then(function (config) {
console.log(config);
});
fs.unlink("temp.txt", function (err) {
if (err) throw err;
console.log("File deleted");
});
The fs module is essential for any Node.js application that handles configuration files, user uploads, logs, or any persistent data stored on disk. Always prefer asynchronous variants inside HTTP servers to keep the event loop free.
Subscribe to continue reading
Get full access to this lesson and all 10 lessons in this course.