Mastering the Node.js File System (fs) Module

Node.js Logo

The Node.js `fs` module provides a rich set of functions to interact with the file system. It's essential for any backend application that needs to read, write, or manage files. This guide covers the most important `fs` methods, emphasizing the modern asynchronous approach.

Synchronous vs. Asynchronous

Almost every method in the `fs` module has a synchronous and an asynchronous form. Asynchronous methods are non-blocking and should always be preferred in a Node.js server environment to avoid blocking the event loop.

Reading Files

The modern way to read files is with `fs.promises.readFile`.

const fs = require('fs').promises;

async function readFileContent(filePath) {
  try {
    const data = await fs.readFile(filePath, 'utf8');
    console.log(data);
  } catch (err) {
    console.error('Error reading file:', err);
  }
}

readFileContent('my-file.txt');

Writing Files

Similarly, use `fs.promises.writeFile` to write data to a file. If the file doesn't exist, it will be created. If it does, it will be overwritten.

const fs = require('fs').promises;

async function writeFileContent(filePath, content) {
  try {
    await fs.writeFile(filePath, content, 'utf8');
    console.log('File written successfully!');
  } catch (err) {
    console.error('Error writing file:', err);
  }
}

writeFileContent('new-file.txt', 'Hello, Node.js!');

Other Useful Methods

  • `fs.promises.appendFile()`: Appends content to a file instead of overwriting it.
  • `fs.promises.readdir()`: Reads the contents of a directory.
  • `fs.promises.stat()`: Gets information about a file or directory (like size, creation date).
  • `fs.promises.unlink()`: Deletes a file.

Comments