How to read files using the fs module

· Category: Node.js

Short answer

Use fs.readFile() for asynchronous reading, fs.readFileSync() for synchronous reading, or fs.promises.readFile() for promise-based reading.

Steps

  1. Import the fs module: const fs = require('fs');.
  2. Asynchronous callback: fs.readFile('file.txt', 'utf8', (err, data) => { ... });.
  3. Synchronous: const data = fs.readFileSync('file.txt', 'utf8');.
  4. Promise-based: const fsPromises = require('fs').promises; await fsPromises.readFile('file.txt', 'utf8');.
  5. Always handle errors to prevent uncaught exceptions.

Tips

  • Use the promise-based API with async/await for cleaner code in modern applications.
  • Specify the encoding (utf8) to receive a string instead of a raw Buffer.

Common issues

  • ENOENT error means the file does not exist at the specified path.
  • Reading very large files into memory with readFile can cause out-of-memory errors; use streams instead.