Skip to content
the poor coder

read json using readFile

Poor Man
Published
Reading time
1 min read
On this page

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:

Text
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:

Text
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.

Keep going

2023

how to sort an array

How to Sort an Array If you have an array and you want to order its elements in a specific way, you need to use a sorting algorithm. There are several sorting algorithms available, but two of the most commonly used are…

javascript2 min read
2023

jquery mobile or desktop

jQuery Mobile or Desktop? As a web developer, I have had some experience with both jQuery Mobile and jQuery Desktop. Both frameworks have their pros and cons, and which one to use really depends on the specific project…

javascript1 min read
2023

node.js folder structure

Node.js Folder Structure If you are new to Node.js, it can be daunting to create a folder structure that will work for your project. The structure you choose will depend on the size and complexity of your project. Here…

javascript1 min read
ESC