I am going to explain to you an example of getting data from json file in node js. Here you will learn How to Fetch Data from Json File in Node JS. if you want to see example of How to Get Data from Json File in Node JS then you are in the right place. let’s discuss in node js to get data from a file. Alright, let’s dive into the steps.
Here you will learn How to Fetch Data from Json File in Node JS. this example will help you How to Get Data from Json File in Node JS. This article goes into detail on node js getting data from a file. So, let's follow a few steps to create an example of how can get data in node js from the file.
Step 1 : Create a JSON file
The first step is to create a JSON file containing the data you want to fetch. You can create the file using any text editor, and save it with a .json extension. Here is an example of a simple JSON file:
"name": "John Doe",
Step 2 : Load the JSON file
To load the JSON file into your Node.js application, you can use the built-in fs module, which provides an API for interacting with the file system. The fs module includes a method called readFileSync, which reads the contents of a file synchronously and returns it as a string.
const fs = require('fs');
const data = fs.readFileSync('data.json', 'utf8');
Step 3 : Parse the JSON data
const jsonData = JSON.parse(data);
Step 4 : Access the JSON data
This code logs the value of the name property of the JSON data to the console.