How to fetch JSON data in Node.js

Hello programmers, Today you will learn how we can fetch JSON data in a Node.js app. Here, our JSON data will be stored in the local machine.

As we are working with files so firstly we will require the fs module in our app. Since it is an inbuilt module we do not need to install it from npm. The syntax for the same is

const fs = require("fs");

The fs module gives us two functions to read files in our local machine which are readFile and readFileSync. The difference between the two is that the readFile method reads the file’s content in an asynchronous way while the latter does it synchronously and hence blocks the event loop and execution of the remaining code until the whole file has been read.

Here, we will be using readFile method to read the JSON data. It accepts a callback function with different parameters. The first one is error and the second one is data.
Till now our code looks like this.

const fs = require("fs");

fs.readFile("file.json", function (err, data) {
});

Now fs module returns the content of the file in JSON string format so we will parse it into a Javascript object using JSON.parse() method. After parsing we can use the data in our program.
The code looks like this.

const fs = require("fs");

fs.readFile("file.json", function (err, data) {
    // If there is any error this line will execute
    if (err) throw err;

    // Here we are converting the data to Javascript object
    const file = JSON.parse(data);

    // Here we are printing the data.
    console.log(file);
});

You may also learn,

Leave a Reply

Your email address will not be published.