Node JS Read and Write Json File Example
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...
Hardik Savani
I'm a full-stack developer, entrepreneur and owner of ItSolutionstuff.com. I live in India and I love to write tutorials and tips that can help to other artisan. I am a big fan of PHP, Laravel, Angular, Vue, Node, Javascript, JQuery, Codeigniter and Bootstrap from the early stage. I believe in Hardworking and Consistency.
We are Recommending you
- How to Get Data from Json File in Node JS?
- How to Remove Element from Array in Node JS?
- How to Push Element in Array in Node JS?
- How to use Underscore JS in Node JS App?
- Node JS Sort Array of Objects by Value Example
- Node JS Foreach Loop Array Example
- How to Create and Use .env File in Node JS?
- Axios HTTP requests in Node JS Example
- Node JS Http Request with Headers Example
- Node JS Make HTTP Put Request Example
- Node JS Make HTTP Delete Request Example