Categories
JavaScript Answers

How to load file with Node.js and JavaScript?

Spread the love

Sometimes, we want to load file with Node.js and JavaScript.

In this article, we’ll look at how to load file with Node.js and JavaScript.

How to load file with Node.js and JavaScript?

To load file with Node.js and JavaScript, we use the readFile method.

For instance, we write

const fs = require("fs");
fs.readFile(__dirname + "/test.txt", (err, data) => {
  if (err) {
    throw err;
  }
  console.log(data.toString());
});

to call fs.readFile with the path to the file.

And we get the file’s content from the data parameter in the callback.

Conclusion

To load file with Node.js and JavaScript, we use the readFile method.

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 *