Inside this article we will see the concept of read and write json file in node js. If you are looking for an article to make you understand of reading and writing a json file in then this tutorial will help you.
You will get more and more from this node js tutorial. Reading and writing json data in node js is a very interesting topic to learn and easy to implement.
For read and write we will use File System (fs) Node Package. It’s a core package in node application.
Node JS is an environment where we can deploy and execute javascript based applications. In this article we will read and write json data using node js.
Learn More –
- How to Generate QR Code in Node JS Tutorial
- How to Get Client IP Address in Node JS
- How to Get Data from Json File in Node Js Tutorial
- Node Express Sequelize ORM CRUD APIs with MySQL
Let’s get started.
Node Js Application Setup
Please make sure you have node and npm both installed. To check available versions use these commands.
To check node version
$ node -v
To check npm version
$ npm -v
Create a folder with any name say readjson. Open this folder into terminal or command prompt.
Next, we need package.json file. Run this given command into terminal
$ npm init -y
The given command will auto generate package.json file with default values.
Next we need to create a file say server.js into node application.
Read a JSON File Data
Open server.js file and write this following code into it.
const fs = require('fs'); let rawdata = fs.readFileSync('data.json'); let users = JSON.parse(rawdata); console.log(users);
Application Testing
Open project terminal and type this command.
$ node server.js
Write Data into JSON File
Open server.js file and write this following code into it.
const fs = require('fs'); users = [{ "id": 1, "name": "Sanjay Kumar" }, { "id": 2, "name": "Ashish Kumar" }, { "id": 3, "name": "Vijay Rohila" }, { "id": 4, "name": "Dhananjay Negi" } ] let data = JSON.stringify(users); fs.writeFileSync('users.json', data);
Application Testing
Open project terminal and type this command.
$ node server.js
We will get a file users.json inside application setup. Inside that file we have the written json data.
[{"id":1,"name":"Sanjay Kumar"},{"id":2,"name":"Ashish Kumar"},{"id":3,"name":"Vijay Rohila"},{"id":4,"name":"Dhananjay Negi"}]
We hope this article helped you to learn How To Read and Write Json File in Node Js Tutorial in a very detailed way.
If you liked this article, then please subscribe to our YouTube Channel for PHP & it’s framework, WordPress, Node Js video tutorials. You can also find us on Twitter and Facebook.