The File System (fs) module in Node.js allows you to work with files on your system. You can create, read, update, and delete files easily.
It is one of the most important core modules used in almost every backend application.
File operations using Node.js fs module (read, write, delete)
1. What is fs Module?
The fs (File System) module is a built-in Node.js module used to interact with files. You don’t need to install it separately.
const fs = require("fs");
2. Reading a File (Synchronous)
const data = fs.readFileSync("file.txt", "utf-8");
console.log(data);
This blocks execution until the file is read.
3. Reading a File (Asynchronous)
fs.readFile("file.txt", "utf-8", (err, data) => {
if (err) throw err;
console.log(data);
});
This does not block execution and is preferred in real applications.
4. Writing a File
fs.writeFile("file.txt", "Hello Node.js", (err) => {
if (err) throw err;
console.log("File written successfully");
});
5. Appending to File
fs.appendFile("file.txt", "\nNew content", (err) => {
if (err) throw err;
});
6. Deleting a File
fs.unlink("file.txt", (err) => {
if (err) throw err;
console.log("File deleted");
});
Always prefer asynchronous methods in real-world applications.
Conclusion
Now you can read, write, and manage files using Node.js.
Your Hero to Zero Node.js journey is now handling real data 📂🚀
Tags
NodeJS