How to Read a file in JavaScript

Reading a file in Javascript (again, nodejs) is as easy as using the built-in method fs.readFile (however it needs to be required first).

fs = require("fs");
fs.readFile("file.js", "utf8", function (err, data) {
  if (err) {
    return console.log(err);
  }
  console.log(data);
});

We require the fs package, and use it’s readFile function to get the contents of the file.js file. Then we console log the contents of it to the stdout. (Or if there is an error e.g. if the file does not exist, we log that instead).

This method is async - there is a sync version as well.

Related Posts