Wednesday, June 17, 2020

Node.js JSON Read Write

Node.js JSON Read Write


Node.js is a JavaScript runtime environment. It is an open-source, cross-platform, asynchronous runtime environment capable of running JavaScript code outside a web browser. It is widely accepted and used in developing APIs and microservices by various organizations.

JSON means for JavaScript Object Notation. JSON is an open standard lightweight format for data interchange. JSON is a format for storing and transporting data consisting of comma-separated attribute-value pairs and array data types. JSON is commonly used to send the information from a server to a web page. 

json syntax



JSON is one of the best ways to interchange data between applications written in different languages. It is very useful to know about how to read and write JSON data to a file in Node.js.

We are discussing, how to handle JSON data with Node in this tutorial. 

Read JSON data using require() method


The easiest way to read a JSON File is require() method. For example, we have a file (named person.json) containing the following data.

[ 
{ 
	"name": "Steve", 
	"age": 31, 
	"skill": ["Java", "PHP", "Python"] 
}, 
{ 
	"name": "Alex", 
	"age": 27, 
	"skill": ["Perl", "Dart", "JavaScript"] 
} 
] 

We can read the data from this file using the following code(named index.js).

const person = require("./person"); 
  
console.log(person); 

The require('path/to/file/filename') method is used. Execute the code using the following command.

node index.js
The results will appear as,

C:\Users\user\Desktop\brackets>node index.js
[
  { name: 'Steve', age: 31, skill: [ 'Java', 'PHP', 'Python' ] },
  { name: 'Alex', age: 27, skill: [ 'Perl', 'Dart', 'JavaScript' ] }
]

Using the fs module 


Read the file


The fs module can also be used to read the JSON file. The fs module returns a file content in a string format. This string can be converted into JSON format by using JSON.parse() in-built method.

var fs = require("fs"); 
   
// Reading person.json file 
fs.readFile("person.json", function(err, data) { 
      
    // handle errors 
    if (err) throw err; 
   
    // Converting to JSON 
    const users = JSON.parse(data); 
      
    console.log(users);  
});

Write to the file


A new user can be added to the person.json file. We can read the file, add data using .push() method, and write the new data to the file using JSON.stringify() method to convert data into a string.

var fs = require("fs"); 

// Read the JSON file 
var person = require("./person"); 

// Define new person
var newperson = { 
	name: "David", 
	age: 33, 
	language: ["TypeScript", "HTML", "Node.js"] 
}; 

// Adding new person to person.json 
person.push(newperson); 

// Write data to the file 
fs.writeFile("person.json", JSON.stringify(person), err => { 
	
	// Handle errors 
	if (err) throw err; 

	// on success prompt success message
	console.log("Data added");  
}); 
The person.json will be appended with new person data.

[
{"name":"Steve","age":31,"skill":["Java","PHP","Python"]},
{"name":"Alex","age":27,"skill":["Perl","Dart","JavaScript"]},
{"name":"David","age":33,"language":["TypeScript","HTML","Node.js"]}
]