Categories
JavaScript Answers

How to store Node.js fs.readfile’s result in a variable and pass to global variable with JavaScript?

Spread the love

Sometimes, we want to store Node.js fs.readfile’s result in a variable and pass to global variable with JavaScript.

In this article, we’ll look at how to store Node.js fs.readfile’s result in a variable and pass to global variable with JavaScript.

How to store Node.js fs.readfile’s result in a variable and pass to global variable with JavaScript?

To store Node.js fs.readfile’s result in a variable and pass to global variable with JavaScript, we can use the version of readFile that returns a promise.

For instance, we write:

const { promises: fs } = require('fs')
const read = async () => {
  const file = await fs.readFile('file.txt')
  console.log(file.toString())
}
read()

to import the promises version of fs with const { promises: fs } = require('fs').

Then we call fs.readFile with the file path.

And we get the read file handle with await and assign it to file.

Then we convert the file content to a string with toString.

Conclusion

To store Node.js fs.readfile’s result in a variable and pass to global variable with JavaScript, we can use the version of readFile that returns a promise.

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 *