How to read a file in Node.js?

I want to read a text file using Node.js. What is the best way to do it?

Answer 1

You can use the fs.readFile method:

const fs = require('fs');
fs.readFile('file.txt', 'utf8', (err, data) => {
  if (err) throw err;
  console.log(data);
});

This reads the entire file asynchronously.

Answer 2

For synchronous reading, use fs.readFileSync:

const data = fs.readFileSync('file.txt', 'utf8');
console.log(data);

This blocks until the file is read.