Node.js “fs” Module With Examples

Node.js, as a server-side JavaScript runtime, provides a rich set of core modules to interact with the file system. The fs module, short for the file system, offers a range of functions for performing file-related operations.

In this tutorial, we’ll explore the key functionalities of the fs module and how it empowers Node.js developers to work with files and directories.

Table of Contents #
  1. Reading Files
  2. Writing Files
  3. Working with Directories
  4. File and Directory Information
  5. Renaming and Deleting
  6. “fs” Module with async/await

Getting Started with the fs Module

The fs module is part of Node.js’s standard library, making it readily available for use in your applications. To start using it, include the module in your script:

const fs = require('fs');

Now, let’s dive into the major features and functions the fs module offers.

1. Reading Files

“fs.readFile()”: Reading the Contents of a File

The fs.readFile() method is used to asynchronously read the contents of a file. It takes the file path and an optional encoding parameter.

const fs = require('fs');
fs.readFile('example.txt', 'utf8', (err, data) => {
    if (err) {
        console.error('Error reading file:', err);
        return;
    }
    console.log('File contents:', data);
});

2. Writing Files

“fs.writeFile()”: Writing Content to a File

The fs.writeFile() method is used to asynchronously write data to a file. It takes the file path, data to be written, an optional encoding parameter, and a callback function.

const fs = require('fs');
const content = 'Hello, Node.js!';
fs.writeFile('output.txt', content, 'utf8', (err) => {
    if (err) {
        console.error('Error writing to file:', err);
        return;
    }
    console.log('File written successfully!');
});

3. Working with Directories

“fs.readdir()”: Reading Contents of a Directory

The fs.readdir() method is used to asynchronously read the contents of a directory. It takes the directory path and a callback function.

const fs = require('fs');
fs.readdir('/path/to/directory', (err, files) => {
    if (err) {
        console.error('Error reading directory:', err);
        return;
    }
    console.log('Directory contents:', files);
});

“fs.mkdir()”: Creating a Directory

The fs.mkdir() method is used to asynchronously create a directory. It takes the directory path and an optional options object.

const fs = require('fs');
fs.mkdir('/path/to/new-directory', { recursive: true }, (err) => {
    if (err) {
        console.error('Error creating directory:', err);
        return;
    }
    console.log('Directory created successfully!');
});

4. File and Directory Information

“fs.stat()”: Retrieving File or Directory Information

The fs.stat() method is used to asynchronously retrieve information about a file or directory. It takes the file or directory path and a callback function.

const fs = require('fs');
fs.stat('example.txt', (err, stats) => {
    if (err) {
        console.error('Error retrieving file information:', err);
        return;
    }
    console.log('File information:', stats);
});

5. Renaming and Deleting

“fs.rename()”: Renaming Files or Directories

The fs.rename() method is used to asynchronously rename a file or directory. It takes the current path, the new path, and a callback function.

const fs = require('fs');
fs.rename('old-file.txt', 'new-file.txt', (err) => {
    if (err) {
        console.error('Error renaming file:', err);
        return;
    }
    console.log('File renamed successfully!');
});

“fs.unlink()”: Deleting Files

The fs.unlink() method is used to asynchronously delete a file. It takes the file path and a callback function.

const fs = require('fs');
fs.unlink('file-to-delete.txt', (err) => {
    if (err) {
        console.error('Error deleting file:', err);
        return;
    }
    console.log('File deleted successfully!');
});

6. “fs” Module with async/await

Adding async/await to file operations can make the code more readable and handle asynchronous operations in a synchronous manner.

Let’s update the examples with async/await:

const fs = require('fs').promises; // Use fs.promises for native promises in Node.js 10.0.0 and later

// Reading Files with async/await
async function readFileExample() {
  try {
    const data = await fs.readFile('example.txt', 'utf8');
    console.log('File contents:', data);
  } catch (err) {
    console.error('Error reading file:', err);
  }
}

// Writing Files with async/await
async function writeFileExample() {
  const content = 'Hello, Node.js!';
  try {
    await fs.writeFile('output.txt', content, 'utf8');
    console.log('File written successfully!');
  } catch (err) {
    console.error('Error writing to file:', err);
  }
}

// Reading Contents of a Directory with async/await
async function readDirectoryExample() {
  try {
    const files = await fs.readdir('/path/to/directory');
    console.log('Directory contents:', files);
  } catch (err) {
    console.error('Error reading directory:', err);
  }
}

// Creating a Directory with async/await
async function createDirectoryExample() {
  try {
    await fs.mkdir('/path/to/new-directory', { recursive: true });
    console.log('Directory created successfully!');
  } catch (err) {
    console.error('Error creating directory:', err);
  }
}

// Retrieving File or Directory Information with async/await
async function statExample() {
  try {
    const stats = await fs.stat('example.txt');
    console.log('File information:', stats);
  } catch (err) {
    console.error('Error retrieving file information:', err);
  }
}

// Renaming Files or Directories with async/await
async function renameExample() {
  try {
    await fs.rename('old-file.txt', 'new-file.txt');
    console.log('File renamed successfully!');
  } catch (err) {
    console.error('Error renaming file:', err);
  }
}

// Deleting Files with async/await
async function unlinkExample() {
  try {
    await fs.unlink('file-to-delete.txt');
    console.log('File deleted successfully!');
  } catch (err) {
    console.error('Error deleting file:', err);
  }
}

// Run examples
readFileExample();
writeFileExample();
readDirectoryExample();
createDirectoryExample();
statExample();
renameExample();
unlinkExample();