NodeJS File System Module: An Introduction

The NodeJS File System module, generally known as fs, allows NodeJS applications to interface with the file system of the operating system on which they are executing. This module includes methods for reading, writing, updating, deleting, and renaming files, making it an indispensable tool for every NodeJS developer. We will go through the many methods given by the fs module and how to utilize them in your NodeJS apps in this post.

Reading files

The fs module includes the fs.readFile() function for reading the contents of a file. The method accepts two arguments: the file path to be read and a callback function to be run after the file has been read.

Example:

const fs = require('fs');

fs.readFile('./example.txt', 'utf-8', (err, data) => {
  if (err) throw err;
  console.log(data);
});

In this example, we first need the fs module before reading the contents of the file example.txt with the fs.readFile() function. The ‘utf-8’ option defines the file’s encoding. Finally, as the second argument, a callback function is supplied. If there is no problem, the file’s contents are logged to the console.

Writing files

The fs module has the fs.writeFile() function for writing to a file. The method accepts three arguments: the path to the file to be written to, the data to be written, and a callback function that is invoked after the write operation is finished.

Example:

const fs = require('fs');

fs.writeFile('./example.txt', 'Hello World!', (err) => {
  if (err) throw err;
  console.log('File written successfully.');
});

In this example, we first import the fs module before using the ‘fs.writeFile()’ function to write the string ‘Hello World!’ to the file example.txt. If no errors occur, the message ‘File written successfully.’ will be shown on the terminal.

Updating files

To update the contents of a file, use fs.readFile() to read the file’s contents, make the required changes, and then use fs.writeFile() to write the revised contents back to the file.

Example:

const fs = require('fs');

fs.readFile('./example.txt', 'utf-8', (err, data) => {
  if (err) throw err;
  const updatedData = data + '\nThis is an update.';
  fs.writeFile('./example.txt', updatedData, (err) => {
    if (err) throw err;
    console.log('File updated successfully.');
  });
});

In this example, we first read the contents of the file example.txt using the ‘fs.readFile()’ function. The file’s contents are then concatenated with the text ‘\nThis is an update.’ before being written back to the file with the ‘fs.writeFile()’ function. If no errors occur, the message ‘File updated successfully.’ will be shown on the terminal.

Deleting files

The fs module has the fs.unlink() function for deleting a file. The method only accepts one argument: the path to the file to be removed.

Example:

const fs = require('fs');

fs.unlink('./example.txt', (err) => {
  if (err) throw err;
  console.log('File deleted successfully.');
});

In this example, we first import the ‘fs’ module and then remove the file ‘example.txt’ using the ‘fs.unlink()’ function. If no errors occur, the message ‘File successfully erased.’ will be written to the terminal.

Renaming Files

To rename a file, use the ‘fs.rename()’ function provided by the ‘fs’ module. The method accepts two arguments: the file’s current path and its new path.

Example:

const fs = require('fs');

fs.rename('./example.txt', './example-renamed.txt', (err) => {
  if (err) throw err;
  console.log('File renamed successfully.');
});

In this example, we first need the ‘fs’ module before renaming the file example.txt to example-renamed.txt using the fs.rename() function. If no errors occur, the message ‘File successfully renamed.’ will be written to the terminal.

Q&A

Q: Can the fs module be used to interact with directories as well as files?

A: Yes, the fs module provides methods for interacting with directories as well as files. Some of these methods include fs.mkdir() for creating directories, fs.readdir() for reading the contents of a directory, and fs.rmdir() for deleting directories.

Exercises

  1. Write a NodeJS script that creates a new file, writes some data to it, reads the contents of the file, updates the contents of the file, and then deletes the file.
  2. Write a NodeJS script that creates a new directory, creates a new file in the directory, writes some data to the file, reads the contents of the file, updates the contents of the file, deletes the file, and then deletes the directory.

Answers

1.

const fs = require('fs');

fs.writeFile('./exercise1.txt', 'Hello World!', (err) => {
  if (err) throw err;
  console.log('File written successfully.');
  fs.readFile('./exercise1.txt', 'utf-8', (err, data) => {
    if (err) throw err;
    console.log(data);
    const updatedData = data + '\nThis is an update.';
    fs.writeFile('./exercise1.txt', updatedData, (err) => {
      if (err) throw err;
      console.log('File updated successfully.');
      fs.unlink('./exercise1.txt', (err) => {
        if (err) throw err;
        console.log('File deleted successfully.'
Scroll to Top