nodejsnotes

Topic 004: File operation in Node.js

Topic 004: File operation in Node.js

Here’s a detailed explanation of handling file operations using Node.js, focusing on both the built-in fs module and the fs-extra package, along with practical examples.

Using the fs Module

The fs (file system) module in Node.js provides a variety of functions to work with the file system. It supports both synchronous and asynchronous operations, but asynchronous methods are generally preferred for non-blocking I/O.

Reading a File Asynchronously

Using fs.readFile, you can read a file without blocking the event loop:

const fs = require("fs");

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

Writing to a File Asynchronously

To write data to a file, use fs.writeFile:

const fs = require("fs");

const content = "This is some example content.";

fs.writeFile("example.txt", content, "utf8", (err) => {
  if (err) {
    console.error("Error writing to the file:", err);
    return;
  }
  console.log("File has been written.");
});

Appending to a File Asynchronously

To append data to a file, use fs.appendFile:

const fs = require("fs");

const content = "\nAppending this text.";

fs.appendFile("example.txt", content, "utf8", (err) => {
  if (err) {
    console.error("Error appending to the file:", err);
    return;
  }
  console.log("Content has been appended.");
});

Deleting a File Asynchronously

To delete a file, use fs.unlink:

const fs = require("fs");

fs.unlink("example.txt", (err) => {
  if (err) {
    console.error("Error deleting the file:", err);
    return;
  }
  console.log("File has been deleted.");
});

Using the fs-extra Package

fs-extra is an npm package that extends the fs module with additional functionality and simplifies common tasks.

Installing fs-extra

First, install the package:

npm install fs-extra

Example Usage of fs-extra

Copying a File

const fs = require("fs-extra");

fs.copy("source.txt", "destination.txt")
  .then(() => {
    console.log("File copied successfully.");
  })
  .catch((err) => {
    console.error("Error copying the file:", err);
  });

Ensuring a Directory Exists

const fs = require("fs-extra");

fs.ensureDir("new-dir")
  .then(() => {
    console.log("Directory ensured.");
  })
  .catch((err) => {
    console.error("Error ensuring directory:", err);
  });

Removing a Directory

const fs = require("fs-extra");

fs.remove("new-dir")
  .then(() => {
    console.log("Directory removed.");
  })
  .catch((err) => {
    console.error("Error removing directory:", err);
  });

Summary

  1. fs Module:

    • Ideal for basic file operations like reading, writing, appending, and deleting files.
    • Provides both synchronous and asynchronous methods.
    • Requires handling callbacks for asynchronous operations, which can be managed using Promises or async/await.
  2. fs-extra Package:

    • Extends fs with more convenient methods for common tasks.
    • Uses Promises, making it easier to handle asynchronous operations, especially with async/await.
    • Includes methods like copy, ensureDir, and remove, which are not available in the default fs module.

By utilizing these tools, you can efficiently manage file operations in your Node.js applications. Whether you need simple file reads and writes or more advanced operations like ensuring directories or copying files, the fs module and fs-extra package have you covered.