fs/promises — File Operations
const fs = require("fs/promises");
const path = require("path");
// Read file:
const content = await fs.readFile("data.txt", "utf8");
const json = JSON.parse(await fs.readFile("data.json", "utf8"));
// Write file:
await fs.writeFile("output.txt", "Hello World");
await fs.appendFile("log.txt", new Date() + ": Event\n");
// File info:
const stats = await fs.stat("file.txt");
stats.isFile(); // true/false
stats.isDirectory(); // true/false
stats.size; // bytes
// Directory operations:
const files = await fs.readdir("./src");
await fs.mkdir("new-dir", { recursive: true });
await fs.rm("old-dir", { recursive: true });
// Check existence:
try {
await fs.access("file.txt");
console.log("File exists");
} catch {
console.log("File not found");
}
// Copy/rename:
await fs.copyFile("src.txt", "dest.txt");
await fs.rename("old-name.txt", "new-name.txt");
path Module
const path = require("path");
// Join paths safely:
const filePath = path.join(__dirname, "data", "users.json");
// Uses correct separator for OS
// Resolve to absolute path:
path.resolve("./config.json"); // full absolute path
// Parse path:
path.basename("/app/data/file.txt"); // "file.txt"
path.dirname("/app/data/file.txt"); // "/app/data"
path.extname("/app/data/file.txt"); // ".txt"
// Build path:
path.join("/app", "data", "file.txt"); // "/app/data/file.txt"
// Practical: config loader:
async function loadConfig(name = "config") {
const configPath = path.join(__dirname, "..", name + ".json");
try {
return JSON.parse(await fs.readFile(configPath, "utf8"));
} catch (e) {
if (e.code === "ENOENT") return {}; // file not found = empty
throw e;
}
}
⚡ Key Takeaways
- Use fs/promises for async file operations — cleaner than callbacks
- path.join() for safe cross-platform paths — never concatenate strings
- Error code ENOENT = file not found; EACCES = permission denied
- { recursive: true } for mkdir creates nested directories
- Always use __dirname for paths relative to the current module
🎯 Practice Exercises
EXERCISE 1
Write a script that scans a directory, counts lines in each .js file, and outputs a report.json with filename and line count for each file.