How to read a text file using Node.js?

Sometimes, we want to read a text file using Node.js.

In this article, we’ll look at how to read a text file using Node.js.

How to read a text file using Node.js?

To read a text file using Node.js, we call fs.readFile.

For instance, we write

const fs = require('fs')

const filename = '/foo/bar.txt'

fs.readFile(filename, 'utf8', (err, data) => {
  if (err) {
    throw err;
  }
  console.log(data)
})

to call fs.readFile with the filename, the encoding of the text file, and a callback that has the read file data stored in the `data parameter.

If there’s an error when reading the file, err is set.

Conclusion

To read a text file using Node.js, we call fs.readFile.