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
- Import the fs module:
const fs = require('fs');. - Asynchronous callback:
fs.readFile('file.txt', 'utf8', (err, data) => { ... });. - Synchronous:
const data = fs.readFileSync('file.txt', 'utf8');. - Promise-based:
const fsPromises = require('fs').promises; await fsPromises.readFile('file.txt', 'utf8');. - 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
ENOENTerror means the file does not exist at the specified path.- Reading very large files into memory with
readFilecan cause out-of-memory errors; use streams instead.