Node JS Read and Write Json File Example

About Us:

We are from free coder. We are a group of web developers who are passionate about web development. You can learn from us php, laravel, node js, vue js, react js and many other topic on web developement.
we are very happy to help you.
free coder

Today what you are going to learn:

Hello Brother,

This post is focused on node js read and write json file. In this article, we will implement a node js write json to file. This article goes in detailed on node js read json file. you can understand a concept of node js read write json file.

In this tutorial, i will give you very simple lesson how to read and write json file in node.js project. let's see very simple lesson here:

Read Json File:

users.json

[

{

"id":1,

"name": "Sagor"

},

{

"id":2,

"name": "Paresh"

},

{

"id":3,

"name": "Rakesh"

},

{

"id":4,

"name": "Mahesh"

}

]

server.js

const fs = require('fs');

let rawdata = fs.readFileSync('users.json');

let users = JSON.parse(rawdata);

console.log(users);

Result:-

[

{ id: 1, name: 'Sagor' },

{ id: 2, name: 'Paresh' },

{ id: 3, name: 'Rakesh' },

{ id: 4, name: 'Mahesh' }

]

Write Json File:

server.js

const fs = require('fs');

users = [

{ id:1, name:'Sagor'},

{ id:2, name:'Paresh'},

{ id:3, name:'Rakesh'},

{ id:4, name:'Mahesh'},

];

let data = JSON.stringify(users);

fs.writeFileSync('users-2.json', data);

Result:- users-2.json

[{"id":1,"name":"Sagor"},{"id":2,"name":"Paresh"},{"id":3,"name":"Rakesh"},{"id":4,"name":"Mahesh"}]

thank you very much for following up with me.

Tags

Recent Posts

Related Posts