0
0
NodejsHow-ToBeginner · 4 min read

How to Use fs Promises in Node.js for Async File Operations

In Node.js, use the fs/promises module to perform file operations with promises, enabling clean async/await syntax. Import it using import fs from 'fs/promises' or const fs = require('fs').promises and then call methods like fs.readFile() or fs.writeFile() which return promises.
📐

Syntax

The fs/promises module provides asynchronous file system methods that return promises. You can import it using ES modules or CommonJS. Each method returns a promise that resolves when the operation completes.

  • Import: import fs from 'fs/promises' or const fs = require('fs').promises
  • Usage: Call methods like fs.readFile(path, options) or fs.writeFile(path, data, options)
  • Returns: A promise that resolves with the result or rejects on error
javascript
import fs from 'fs/promises';

async function example() {
  const data = await fs.readFile('file.txt', 'utf8');
  await fs.writeFile('file-copy.txt', data);
}
💻

Example

This example reads the content of example.txt asynchronously and writes it to copy.txt. It uses async/await for clear, readable code without callbacks.

javascript
import fs from 'fs/promises';

async function copyFile() {
  try {
    const content = await fs.readFile('example.txt', 'utf8');
    await fs.writeFile('copy.txt', content);
    console.log('File copied successfully');
  } catch (error) {
    console.error('Error:', error);
  }
}

copyFile();
Output
File copied successfully
⚠️

Common Pitfalls

Common mistakes include:

  • Not importing fs/promises correctly, causing undefined errors.
  • Forgetting to use await or .then(), leading to unresolved promises.
  • Not handling errors with try/catch or .catch(), which can crash the app.

Always use async/await with fs/promises methods and handle errors properly.

javascript
import fs from 'fs/promises';

// Wrong: missing await, no error handling
function readFileWrong() {
  const data = fs.readFile('file.txt', 'utf8');
  console.log(data); // Prints a Promise, not file content
}

// Right: await with try/catch
async function readFileRight() {
  try {
    const data = await fs.readFile('file.txt', 'utf8');
    console.log(data);
  } catch (err) {
    console.error('Failed to read file:', err);
  }
}
📊

Quick Reference

MethodDescriptionReturns
fs.readFile(path, options)Reads file content asynchronouslyPromise
fs.writeFile(path, data, options)Writes data to a file asynchronouslyPromise
fs.appendFile(path, data, options)Appends data to a file asynchronouslyPromise
fs.unlink(path)Deletes a file asynchronouslyPromise
fs.mkdir(path, options)Creates a directory asynchronouslyPromise

Key Takeaways

Use the fs/promises module to work with files asynchronously using promises.
Always use async/await or .then() to handle the promises returned by fs methods.
Handle errors with try/catch blocks to avoid unhandled promise rejections.
Import fs/promises correctly to access promise-based file system methods.
Common methods include readFile, writeFile, appendFile, unlink, and mkdir.