Categories
JavaScript Answers

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

Spread the love

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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *