0
0
NodejsHow-ToBeginner · 3 min read

How to Read File Asynchronously in Node.js with fs.promises

In Node.js, you can read files asynchronously using the fs.promises.readFile method which returns a Promise. This allows you to use async/await syntax for clean, non-blocking file reading.
📐

Syntax

The fs.promises.readFile method reads a file asynchronously and returns a Promise that resolves with the file content as a Buffer or string.

  • path: The file path to read.
  • options: Optional settings like encoding (e.g., 'utf8').
  • Returns a Promise that resolves with the file data.
javascript
import { promises as fs } from 'fs';

async function readFileAsync() {
  const data = await fs.readFile('path/to/file.txt', { encoding: 'utf8' });
  return data;
}
💻

Example

This example shows how to read a text file asynchronously using async/await. It prints the file content to the console without blocking the program.

javascript
import { promises as fs } from 'fs';

async function readFileExample() {
  try {
    const content = await fs.readFile('example.txt', { encoding: 'utf8' });
    console.log('File content:', content);
  } catch (error) {
    console.error('Error reading file:', error.message);
  }
}

readFileExample();
Output
File content: This is an example file content.
⚠️

Common Pitfalls

Common mistakes include:

  • Not using await or .then() to handle the Promise, causing unexpected behavior.
  • Forgetting to specify encoding, which returns a Buffer instead of a string.
  • Not handling errors with try/catch or .catch(), which can crash the program.
javascript
import { promises as fs } from 'fs';

// Wrong: Missing await, returns a Promise object
const data = fs.readFile('example.txt', { encoding: 'utf8' });
console.log(data); // Prints: Promise { <pending> }

// Right: Using await inside async function
async function readCorrect() {
  try {
    const content = await fs.readFile('example.txt', { encoding: 'utf8' });
    console.log(content);
  } catch (err) {
    console.error(err);
  }
}
readCorrect();
Output
Promise { <pending> } This is an example file content.
📊

Quick Reference

Remember these tips when reading files asynchronously in Node.js:

  • Use fs.promises.readFile for Promise-based async file reading.
  • Always specify encoding: 'utf8' to get a string instead of a Buffer.
  • Use async/await or .then() to handle the Promise.
  • Handle errors with try/catch or .catch().

Key Takeaways

Use fs.promises.readFile with async/await for clean asynchronous file reading.
Always specify encoding to get readable string data instead of raw Buffer.
Handle errors properly to avoid crashes when reading files.
Avoid forgetting await which causes unresolved Promise outputs.
fs.promises API is modern and preferred over callback-based fs.readFile.