How to Fetch Data from JSON file in Node JS

In this tutorial, you will learn how to get or fetch data from a JSON file using readfile() and readfilesync() of fs module in node js.

How to Get/Read Data from JSON File in Node JS?

Here are steps:

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:

{
    "name": "John Doe",
    "age": 30,
    "email": "[email protected]"
}

Step 2: Read the JSON file

To read or get 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:

const fs = require('fs');
const data = fs.readFileSync('data.json', 'utf8');

Step 3: Parse the JSON data

To parse the JSON data, use the built-in JSON.parse method, which takes a JSON string as input and returns a JavaScript object:

const jsonData = JSON.parse(data);

Step 4: Access the JSON data

Now that you have loaded and parsed the JSON data, and can access it just like any other JavaScript object:

console.log(jsonData.name);

Conclusion

That’s it, you have learned how to read and parse JSON data in Node.js.

Recommended Node JS Tutorials

AuthorDevendra Dode

Greetings, I'm Devendra Dode, a full-stack developer, entrepreneur, and the proud owner of Tutsmake.com. My passion lies in crafting informative tutorials and offering valuable tips to assist fellow developers on their coding journey. Within my content, I cover a spectrum of technologies, including PHP, Python, JavaScript, jQuery, Laravel, Livewire, CodeIgniter, Node.js, Express.js, Vue.js, Angular.js, React.js, MySQL, MongoDB, REST APIs, Windows, XAMPP, Linux, Ubuntu, Amazon AWS, Composer, SEO, WordPress, SSL, and Bootstrap. Whether you're starting out or looking for advanced examples, I provide step-by-step guides and practical demonstrations to make your learning experience seamless. Let's explore the diverse realms of coding together.

Leave a Reply

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