Node JS Read and Write Json File Example

By Hardik Savani May 29, 2021 Category : Node JS

Hi,

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 example how to read and write json file in node.js project. let's see very simple example here:

Read Json File:

users.json

[

{

"id":1,

"name": "Hardik"

},

{

"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);

Output:

[

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

{ 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:'Hardik'},

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

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

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

];

let data = JSON.stringify(users);

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

Output: users-2.json

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

i hope it can help you...

Tags :
Shares