patternjavascriptMinor
Using global variables in my node.js program configuration
Viewed 0 times
globalnodeprogramusingvariablesconfiguration
Problem
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
server.js file
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);
};
}
});Solution
You say you're using globals because "I have added a watch function to watch for the changes in the config.json file". You don't need globals for this. If you declare the variables at the top level, like you've done with
"I know using global variables in JavaScript is bad practice." Using global variables in any language is bad practice if you can avoid it.
*A function like this, which uses variables declared outside the function, is called a "closure".
http and server, they'll be accessible everywhere in your script, including inside the anonymous function where you're using them.* You could get rid of the (function() { ... })(); wrapper round the first bit (not sure why you've wrapped that bit) and then declare them there."I know using global variables in JavaScript is bad practice." Using global variables in any language is bad practice if you can avoid it.
*A function like this, which uses variables declared outside the function, is called a "closure".
Context
StackExchange Code Review Q#51700, answer score: 2
Revisions (0)
No revisions yet.