How to Fetch Data from Json File in Node JS

Sourabh Mourya

Sourabh Mourya

Sr. Software Developer
Share on facebook
Share on twitter
Share on pinterest
Share on linkedin

In Node.js, you can fetch data from a JSON file using the built-in fs (file system) module. Here’s an example of how you can read data from a JSON file:

  1. First, require the fs module:
const fs = require('fs');

2. Next, use the fs.readFile() method to read the contents of the JSON file. This method takes two parameters: the path to the file and a callback function that will be called when the file is read. The callback function takes two parameters: an error (if one occurred) and the contents of the file.

fs.readFile('path/to/your/file.json', (err, data) => {
  if (err) throw err;

  // do something with the data
});

3. Once the file has been read, you can parse the JSON data using JSON.parse(). This method takes a JSON string and converts it into a JavaScript object.

fs.readFile('path/to/your/file.json', (err, data) => {
  if (err) throw err;

  const jsonData = JSON.parse(data);

  // do something with the jsonData object
});
  1. Finally, you can use the data in your application as needed.

Here’s the complete code to fetch data from a JSON file:

const fs = require('fs');

fs.readFile('path/to/your/file.json', (err, data) => {
  if (err) throw err;

  const jsonData = JSON.parse(data);

  console.log(jsonData); // log the data to the console
});
Suppose we have a data.json file with the following content:
{
  "name": "John Doe",
  "age": 30,
  "address": {
    "street": "123 Main St",
    "city": "Anytown",
    "state": "CA",
    "zip": "12345"
  },
  "phoneNumbers": [
    {
      "type": "home",
      "number": "555-555-1234"
    },
    {
      "type": "work",
      "number": "555-555-5678"
    }
  ]
}

To fetch the data from this file, we can use the following code:

const fs = require('fs');

fs.readFile('data.json', (err, data) => {
  if (err) throw err;

  const jsonData = JSON.parse(data);

  console.log(jsonData.name); // output: John Doe
  console.log(jsonData.age); // output: 30
  console.log(jsonData.address.street); // output: 123 Main St
  console.log(jsonData.phoneNumbers[0].number); // output: 555-555-1234
});

In this example, we first require the fs module and then use the fs.readFile() method to read the contents of the data.json file. We pass in a callback function that takes an error (if one occurred) and the contents of the file.

Inside the callback function, we use the JSON.parse() method to convert the JSON data into a JavaScript object. We can then access the properties of the object as needed. In this example, we log the values of the name, age, address.street, and phoneNumbers[0].number properties to the console.

Leave a Reply

Your email address will not be published. Required fields are marked *

Related Stories