How to Read a file in JavaScript Posted in Polyglotbits on 27 of Nov, 2015

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);

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.