read json using readFile

How to Read JSON using readFile in Node.js

If you are working with Node.js, you might come across situations where you need to read JSON files. Node.js provides a built-in module called fs (file system) that allows you to interact with the file system. You can use this module to read JSON files using the readFile() method.

Using readFile() Method

The readFile() method is used to read files asynchronously in Node.js. This method takes two arguments: the path of the file to be read and an optional encoding type.

The following code demonstrates how to read a JSON file using the readFile() method:

const fs = require('fs');

fs.readFile('data.json', 'utf8', (err, data) => {
  if (err) {
    console.log(err);
  } else {
    console.log(data);
  }
});
  • The first argument is the path of the JSON file.
  • The second argument is the encoding type. In this case, we use utf8 encoding because the JSON file is a text file.
  • The third argument is a callback function that takes two arguments: an error object and the data read from the file.
  • If an error occurs while reading the file, the error object will be passed to the callback function. Otherwise, the data read from the file will be passed to the callback function.

Using require() Method

Another way to read JSON files is to use the require() method. This method is synchronous and doesn't require a callback function.

The following code demonstrates how to read a JSON file using the require() method:

const data = require('./data.json');

console.log(data);
  • The argument to require() is the path of the JSON file.
  • The data from the JSON file is returned by the require() method and stored in the data variable.

Conclusion

Both readFile() and require() methods can be used to read JSON files in Node.js. If you need to read files asynchronously, use the readFile() method. If you need to read files synchronously, use the require() method.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe