Skip to main content

File System Module

As a Node.js developer, mastering the fs (File System) module is essential. Whether you're building a simple script or a complex application, the ability to read, write, and manipulate files is crucial. In this guide, we'll dive deep into the fs module, covering everything you need to know, including working with JSON files.

Introduction to the fs Module

The fs module is a core module in Node.js that allows you to interact with the file system. Since it’s built into Node.js, you don’t need to install any additional packages to use it. To get started, simply require the module in your script:

Importing the fs module
const fs = require("fs");

or using ES6 modules:

Importing the fs module using ES6 modules
import fs from "fs";

The fs module provides a wide range of methods for working with files and directories, including reading, writing, updating, and deleting files, as well as creating, reading, and deleting directories.

Synchronous vs Asynchronous Methods

In Node.js, most operations are asynchronous by nature. This means that while one operation is being processed, other code can continue to execute. The fs module provides both asynchronous and synchronous methods for file operations.

  • Asynchronous methods: These methods are non-blocking and allow other code to run while the operation is in progress.
  • Synchronous methods: These methods block the execution of the program until the operation is completed. They are often used when you need to ensure that one operation is fully complete before starting another.

Reading Files

Asynchronous Reading

Using the asynchronous readFile method, you can read a file without blocking the execution of your code:

Reading a file asynchronously
fs.readFile("example.txt", "utf8", (err, data) => {
if (err) throw err;
console.log(data);
});

In this example, readFile reads the contents of example.txt. The utf8 encoding ensures that the file content is returned as a string.

Synchronous Reading

If you prefer to block execution until the file is fully read, use readFileSync:

Reading a file synchronously
try {
const data = fs.readFileSync("example.txt", "utf8");
console.log(data);
} catch (err) {
console.error(err);
}

This synchronous method returns the file content immediately, or throws an error if something goes wrong.

Writing and Updating Files

Asynchronous Writing

To write data to a file asynchronously, use writeFile:

Writing to a file asynchronously
fs.writeFile("example.txt", "Hello, Rizwan!", (err) => {
if (err) throw err;
console.log("File has been saved!");
});

This will create example.txt if it doesn’t exist, or overwrite it if it does, writing "Hello, Rizwan!" to the file.

Synchronous Writing

For a synchronous write operation, use writeFileSync:

Writing to a file synchronously
try {
fs.writeFileSync("example.txt", "Hello, Rizwan!");
console.log("File has been saved!");
} catch (err) {
console.error(err);
}

This method writes the data to the file and returns once the operation is complete.

Appending Data

If you need to add data to an existing file without overwriting it, use appendFile or appendFileSync:

Appending data to a file
fs.appendFile("example.txt", "\nAppended text for Rizwan.", (err) => {
if (err) throw err;
console.log("Data appended!");
});

Working with Directories

Creating Directories

You can create a directory using mkdir:

Creating a directory
fs.mkdir("newDir", (err) => {
if (err) throw err;
console.log("Directory created!");
});

For creating nested directories, set the recursive option to true:

Creating nested directories
fs.mkdir("path/to/newDir", { recursive: true }, (err) => {
if (err) throw err;
console.log("Nested directories created!");
});

Reading Directories

To read the contents of a directory, use readdir:

Reading a directory
fs.readdir("path/to/dir", (err, files) => {
if (err) throw err;
console.log(files); // Logs an array of file names
});

Deleting Directories

To delete a directory, use rmdir:

Deleting a directory
fs.rmdir("path/to/dir", (err) => {
if (err) throw err;
console.log("Directory deleted!");
});

To delete a directory and all its contents, use fs.rm() with the recursive option (fs.rmdir with recursive was deprecated in Node.js 16):

Deleting a directory and its contents
fs.rm("path/to/dir", { recursive: true, force: true }, (err) => {
if (err) throw err;
console.log("Directory and its contents deleted!");
});

Deleting Files

To delete a file, use the unlink method:

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

Working with JSON Files

JSON files are a common way to store data in Node.js applications. The fs module makes it easy to read from and write to JSON files.

Reading JSON Files

To read a JSON file, use readFile and then parse the data:

Reading a JSON file
fs.readFile("data.json", "utf8", (err, data) => {
if (err) throw err;
const jsonData = JSON.parse(data);
console.log(jsonData);
});

Here, JSON.parse is used to convert the file's content into a JavaScript object.

Writing JSON Files

Writing JSON to a file involves converting a JavaScript object to a JSON string with JSON.stringify, then saving it with writeFile:

Writing JSON data to a file
const jsonData = {
name: "Rizwan",
age: 30,
city: "New York",
};

fs.writeFile("data.json", JSON.stringify(jsonData, null, 2), (err) => {
if (err) throw err;
console.log("JSON data saved!");
});

The null parameter is for replacing values (which we don’t need here), and the 2 parameter is for formatting the JSON string with indentation.

Conclusion

The fs module is a powerful tool for file manipulation in Node.js. Whether you're working with text files, directories, or JSON data, fs provides a comprehensive set of methods for your needs. Understanding both synchronous and asynchronous operations will allow you to handle file operations effectively in your applications.

By mastering the fs module, you'll be well-equipped to handle a wide range of tasks in your Node.js projects. Experiment with the examples provided, and you'll soon be proficient in managing files and directories with ease.

Happy coding!