How to read file with async and await in Node.js?

Sometimes, we want to read file with async and await in Node.js.

In this article, we’ll look at how to read file with async and await in Node.js.

How to read file with async and await in Node.js?

To read file with async and await in Node.js, we can use the promise version of fs.readFile.

For instance, we write

const fs = require('fs').promises;

const read = async () => {
  const data = await fs.readFile("monolitic.txt", "binary");
  return new Buffer(data);
}

to define the read function that calls fs.readFile with fs returned from the promises property of the fs module.

This version of readFile will return a promise.

It takes the file path and the encoding of the file.

And we get the file data from the promise’s resolve value.

Therefore, data has the file data.

Conclusion

To read file with async and await in Node.js, we can use the promise version of fs.readFile.