Home
Tools
Workshops
Technologies
Pricing
Contact Us



Essentials of Node.js

Part-6 Node.js Manipulating JSON

Brief Introduction
JSON or Java Script Object Notation is a format for data exchange and it is one of the most commonly used format for data exchange in modern times. In this tutorial we'll expand our horizons in Node.js by understanding how to manipulate json files in Node.js and how we can use json files as configurations files. To conclude this tutorial we'll also look at how we can constantly monitor a file for changes in Node.js
Writing a JSON file
Just like javascript objects, JSON documents are simply a set a key-value pairs. When storing json objects to a file, we use a .json extension. Using our knowledge from previous tutorial, let's write a json file with some keys and values.

/**
		@name:        WriteJSON.js
		@description: A Simple Program to write data to a file asynchronously. 
		@author: 	  @rishabhio
*/
var fs = require('fs');


var stocks = {
	"toothpaste": 6,
	"bathsoap": 10,
	"toothbrush": 34,
	"shampoo": 12,
	"facewash": 4
}
// note the JSON.stringify() methods being used to convert object to a string for storage in file 
fs.writeFile('stocks.json', JSON.stringify(stocks) ,function(error){
	console.log('finished writing!');
});
	
Execution of above program.


you@yourpc ~
$ node WriteJSON.js
finished writing!
 
	
Reading back JSON object

/**
		@name:        ReadJSON.js
		@description: A Simple Program to write data to a file asynchronously. 
		@author: 	  @rishabhio
*/
var fs = require('fs');

var contents = fs.readFileSync('stocks.json');
obj = JSON.parse(contents);				// convert string representation back to object representation. 
console.log(obj);
	
	


you@yourpc ~
$ node ReadJSON.js
{ toothpaste: 6,
  bathsoap: 10,
  toothbrush: 34,
  shampoo: 12,
  facewash: 4 }

	
What do we learn ?
We can use 2 methods JSON.stringify and JSON.parse to perform object->string and string->object transformations. We'll see use cases of JSON format in upcoming tutorials as it is one of the most commonly used methods for data exchange in modern web apps and mobile apps.
Monitoring a File for change
What if want to be notified about changes in a file in real time e.g. we need to be notified each time somebody changes the values in the stocks.json file above.
Node.js fs module provides a special function watchfile for this purpose. This function takes name of file and a callback function as parameters and it fires the callback each time a change is detected in the file being monitored. Following is a code snippet to monitor the stocks.json file we wrote above.

/**
		@name:        MonitorFile.js
		@description: A Simple Program to monitor a file in real time. 
		@author: 	  @rishabhio
*/
var fs = require('fs');

fs.watchFile('stocks.json',function(original,changed){
	console.log(' File Changed ');
	stocks_new = JSON.parse(fs.readFileSync('stocks.json'));
	console.log('Changed file: ',stocks_new);
});
	
	

you@yourpc ~
$ MonitorFile.js
 File Changed
Changed file:  { toothpaste: 6,
  bathsoap: 10,
  toothbrush: 34,
  shampoo: 12,
  facewash: 3 }

Note that in order to see the output on screen, you'll have to manually change the contents of the stocks.json file.






developed & nourished with by rishabh.io