Chapter 3 of 12
The fs module lets Node.js read and write files, create directories, and manage the file system — essential for building scripts, tools, servers that serve files, and data processing pipelines.
const fs = require("fs");
const path = require("path");
// Synchronous — blocks until done (fine for scripts, bad for servers)
const content = fs.readFileSync("data.txt", "utf8");
console.log(content);
// Asynchronous — non-blocking (preferred for servers)
fs.readFile("data.txt", "utf8", (error, content) => {
if (error) {
console.error("Error reading file:", error);
return;
}
console.log(content);
});
// Promise-based (cleanest — use this)
const fsPromises = require("fs/promises");
async function readData() {
const content = await fsPromises.readFile("data.txt", "utf8");
const json = JSON.parse(content);
return json;
}const { writeFile, mkdir, readdir, stat, unlink } = require("fs/promises");
const path = require("path");
// Write a file (creates it if it doesn't exist)
await writeFile("output.txt", "Hello, World!", "utf8");
// Write JSON
const data = { users: 100, courses: 12 };
await writeFile("data.json", JSON.stringify(data, null, 2));
// Create a directory
await mkdir("./logs", { recursive: true }); // recursive: no error if exists
// List directory contents
const files = await readdir("./src");
console.log(files); // ["app.js", "utils.js", ...]
// Check if a file/directory exists
try {
const info = await stat("./data.json");
console.log("Is file:", info.isFile());
console.log("Size:", info.size, "bytes");
} catch {
console.log("File does not exist");
}
// Delete a file
await unlink("./temp.txt");TIP
Use path.join() for all file paths. Never concatenate paths with string templates. path.join(__dirname, 'data', 'courses.json') works correctly on Windows (which uses backslashes) and Unix systems (forward slashes). String templates will break on Windows.