fs.promises

The fs.promises API is the modern way to interact with the file system in Node.js. It provides an alternative to the traditional error-first callbacks, allowing you to use Promises and Async/Await for cleaner, more readable code.

1. Why use fs.promises?


Before this API, if you wanted to read a file and then write to another, you would end up with "Callback Hell." With fs.promises, the code stays flat and follows a logical top-to-bottom flow.

Key Advantages:

  • Avoids Nesting: No more deep indentations.

  • Better Error Handling: Use standard try/catch blocks.

  • Built-in: No need for util.promisify anymore.


2. How to Import

You can access the promises API in two ways:

CommonJS:

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

ES Modules (ESM):
JavaScript
import fs from 'fs/promises';


3. Common Operations with Async/Await


Reading a File

The readFile method returns a promise that resolves with the file content.

Using 'utf8' ensures you get a string instead of a Buffer.


async function readMyFile() {
  try {
    const data = await fs.readFile('./config.json', 'utf8');
    console.log(JSON.parse(data));
  } catch (err) {
    console.error("Error reading file:", err.message);
  }
}


Writing and Appending


  • writeFile: Replaces the file if it exists or creates a new one.

  • appendFile: Adds data to the end of the file.


async function manageLogs() {
  try {
    await fs.writeFile('log.txt', 'First Log Entry\n');
    await fs.appendFile('log.txt', 'Second Log Entry\n');
    console.log("File updated successfully!");
  } catch (err) {
    console.error(err);
  }
}

Checking File Existence and Stats

Instead of fs.exists (which is deprecated), you use fs.access or fs.stat.


async function checkFile(path) {
  try {
    await fs.access(path); // Resolves if file exists and is accessible
    const stats = await fs.stat(path);
    console.log(`File size: ${stats.size} bytes`);
  } catch {
    console.log("File does not exist.");
  }
}


5. Useful fs.promises Methods


Method Description
fs.mkdir() Creates a directory.
fs.readdir() Reads the contents of a directory (returns an array of filenames).
fs.rename() Renames or moves a file.
fs.unlink() Deletes a file.
fs.rm() Deletes a file or directory (recursively if requested).