I know using global variables in JavaScript is bad practice. Here I am using config, host and port as global variables as I have added a watch function to watch for the changes in the config.json file. Is the use of global variables in this example a bad practice or is it ok to use them?
config.json file
{
"host":"127.0.0.1",
"port":8000
}
server.js file
(function(){
var fs = require("fs");
config = JSON.parse(fs.readFileSync("config.json")); //global variable
host = config.host; //global variable
port = config.port; //global variable
})();
var http = require("http");
var server = http.createServer(function(request,response){
response.writeHead(200,{"Content-Type":"text/plain"});
response.end("Hello World");
});
server.listen(port,host,function(){
console.log("Server listening at:"+host+" on port:"+port);
});
fs.watchFile("config.json",function(){
config = JSON.parse(fs.readFileSync("config.json")); //global variable(overwritten)
host = config.host; //global variable(overwritten)
port = config.port; //global variable(overwritten)
server.close();
server.listen(port,host,function(){
console.log("Server listening at:"+host+" on port:"+port);
};
}
});