Beginner Fundamentals
The fs Module
The fs (file system) module lets you work with files: read, write, append, and delete. It is built into Node.js, so no installation is needed.
Reading a file (async)
The async version takes a callback and does not block the program.
const fs = require("fs");
fs.readFile("note.txt", "utf8", (err, data) => {
if (err) {
return console.error(err);
}
console.log(data);
});
Writing a file (async)
const fs = require("fs");
fs.writeFile("note.txt", "Hello file!", (err) => {
if (err) throw err;
console.log("File saved");
});
Synchronous versions
The sync versions block until done. They are simpler but stop everything while running.
const fs = require("fs");
const data = fs.readFileSync("note.txt", "utf8");
console.log(data);
fs.writeFileSync("note.txt", "New content");
Sync vs async
- Use async in servers so other work continues.
- Use sync only for simple scripts or startup code.
Summary
The fs module is your gateway to files. Prefer the async methods for anything that handles many requests.