Back to roadmaps nodejs Course

File System fs Module

The Node.js File System (fs) module allows you to interact with the file system on your operating system. It provides multiple API flavors: Synchronous (blocking), Callback-based (asynchronous), and Promise-based (asynchronous).


1. The Three API Flavors

Synchronous API (Blocking)

Blocks execution of the main thread until the I/O operation is complete. Avoid using this in web servers.

import fs from "fs";

// Blocks execution flow
try {
  const data = fs.readFileSync("input.txt", "utf8");
  console.log("Sync content:", data);
} catch (err) {
  console.error("Read error:", err);
}

Callback-based API (Non-Blocking)

Runs asynchronously using callback functions. This avoids blocking but can lead to deeply nested code (Callback Hell).

import fs from "fs";

fs.readFile("input.txt", "utf8", (err, data) => {
  if (err) {
    console.error("Error reading file:", err);
    return;
  }
  console.log("Async Callback content:", data);
});

Promise-based API (Modern, Non-Blocking)

Allows writing cleaner asynchronous code using async/await syntax. Highly recommended for modern Node.js applications.

import fs from "fs/promises";

async function readFileContent() {
  try {
    const data = await fs.readFile("input.txt", "utf8");
    console.log("Promise-based content:", data);
  } catch (err) {
    console.error("Async read error:", err);
  }
}

readFileContent();

2. Writing and Appending Files

You can write new data or append content to existing files using the promises API:

import fs from "fs/promises";

async function fileOperations() {
  const filePath = "output.txt";
  
  // Write fresh content (overwrites if file already exists)
  await fs.writeFile(filePath, "Hello World from Node.js\n", "utf8");
  
  // Append content to the end of the file
  await fs.appendFile(filePath, "Appending a second line\n", "utf8");
  
  console.log("Write and append operations complete");
}

fileOperations();

3. Directory Operations

The fs module also provides utilities to create, read, and delete directories, as well as fetch metadata (like file size or permissions):

import fs from "fs/promises";

async function directoryDemo() {
  const dirPath = "./sandbox";
  
  // Create a directory if it does not exist
  await fs.mkdir(dirPath, { recursive: true });
  
  // Read all files inside a directory
  const files = await fs.readdir("./");
  console.log("Files list:", files);
  
  // Fetch detailed metadata of a file or folder
  const stats = await fs.stat("output.txt");
  console.log("Is File:", stats.isFile());
  console.log("File Size in Bytes:", stats.size);
  
  // Delete a file
  await fs.unlink("output.txt");
  
  // Remove a directory
  await fs.rm(dirPath, { recursive: true, force: true });
}

directoryDemo();
Published on Last updated: