📂 Node.js File System (fs) Module

Last Updated: 26th October 2025


  • The fs module allows you to interact with the file system in Node.js.
  • You can read, write, update, delete, and manage files and directories.

Hinglish Tip 🗣: Socho fs module ek “file manager” hai Node.js ke liye — terminal ki tarah files ko manipulate kar sakte ho programmatically.


Importing fs Module

// CommonJS
const fs = require("fs");

// ES6 Module (Node >= 14 with type="module")
import fs from "fs";

Common File Operations

  1. Read File
// Asynchronous
fs.readFile("example.txt", "utf8", (err, data) => {
  if (err) throw err;
  console.log(data);
});

// Synchronous
const dataSync = fs.readFileSync("example.txt", "utf8");
console.log(dataSync);

  1. Write File
// Asynchronous
fs.writeFile("example.txt", "Hello Node.js!", (err) => {
  if (err) throw err;
  console.log("File written successfully!");
});

// Synchronous
fs.writeFileSync("example.txt", "Hello Node.js!");
console.log("File written successfully!");

  1. Append File
fs.appendFile("example.txt", "\nAppending some text", (err) => {
  if (err) throw err;
  console.log("Text appended!");
});

  1. Delete File
fs.unlink("example.txt", (err) => {
  if (err) throw err;
  console.log("File deleted!");
});

  1. Rename File
fs.rename("example.txt", "example2.txt", (err) => {
  if (err) throw err;
  console.log("File renamed!");
});

  1. Check if File Exists
fs.exists("example.txt", (exists) => {
  console.log(exists ? "File exists" : "File does not exist");
});

  1. Create Directory
// Create directory
fs.mkdirSync("myFolder");

// Remove directory
fs.rmdirSync("myFolder");

💡 Quick Practice

  • Create a file notes.txt and write your name in it.
  • Append the current date to the same file.
  • Read and print the content of notes.txt.
  • Delete the file after verification.