Import_Config_file_NodeJs


Here we can make our work more easier because we can list our data in json file and call the needed data in application. In this example I defined the host and port address in config file and call the values in my project file. Also here we are using watch class from file system module. This is very help full in real time server management. Because without stopping the server the port and host address can be changeable. For example if we have the address for the host and port in config.json then it can be update in realtime without stopping the server.

Sample of config file
save as config.json (name can be vary)
{
"port" : 1336,
"host" : "127.1.1.1"
}


var http = require("http");

var file = require("fs");

console.log("Starting");

/* Call the JSON formatted config file to read the host and port values . Here we used the readFileSync class from File system module. The FileSync class use to make wait the bellow code until it read the config file - After Sync only the other code will proceed */
var config = JSON.parse(file.readFileSync("config.json"));

// Host and Port Address which are read from config
var host = config.host;
var port = config.port;

var server = http.createServer(
function(request,response){
console.log("Received request: " + request.url);
//here “.” space we have to define our file path Ex: ./Dir
file.readFile("." + request.url,
function(error,data){
if(error){
response.writeHead(404,{"Content-type":"text/plain"});
response.end("Sorry the page was not found");
}else{
response.writeHead(200,{"Content-type":"text/Html"});
response.end(data);
}
});
});

server.listen(port,host,
function(){
console.log("listening " + host + ":" + port);
}
);



/*The watchFile class is automatically search for any changes in config file with the frequent time interval. If it get any update from that file. Then it will return to the system with the changes*/
file.watchFile("config.json",
function(){
config = JSON.parse(file.readFileSync("config.json"));
server.close();
host = config.host;
port = config.port;
//Listen to newport when we update the config.json file
server.listen(port,host,
function(){
console.log("New listening " + host + ":" + port);
});
});



1 comment: