8. File System (fs) Module – Reading & Writing Files in Node.js

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.

Node.js fs module

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 📂🚀

Chakrapani U

Hi, I’m Chakrapani Upadhyaya, an IT professional with 15+ years of industry experience. Over the years, I have worked on web development, enterprise applications, database systems, and cloud-based solutions. Through this blog, I aim to simplify complex technical concepts and help learners grow from beginners to confident, industry-ready developers.

Previous Post Next Post

نموذج الاتصال