How to read a JSON file into server memory with Node.js?

Sometimes, we want to read a JSON file into server memory with Node.js.

In this article, we’ll look at how to read a JSON file into server memory with Node.js.

How to read a JSON file into server memory with Node.js?

To read a JSON file into server memory with Node.js, we can use the readFile or readFileSync method.

For instance, we write

const fs = require('fs');
fs.readFile('file', 'utf8', (err, data) => {
  if (err) {
    throw err;
  }
  const obj = JSON.parse(data);
});

to call fs.readFile with the file path, encoding of the file we’re reading, and a callback that runs when the method is done running.

If there’s an error, err is set and we throw it.

Otherwise, we call JSON.parse with the file data we read.

readFile reads the file asynchronously.

We can read JSON files synchronously with readFileSync.

To use it, we write

const fs = require('fs');
const obj = JSON.parse(fs.readFileSync('file', 'utf8'));

to call it with the file path and encoding and return the file directly.

And then we call JSON.parse on the returned string file contents.

Conclusion

To read a JSON file into server memory with Node.js, we can use the readFile or readFileSync method.