What do you guys think about making constants in Javascript. I want to do it in the best possible way. I know that constants do not really exist but I wrote this and I was not able to change the values after the export.
Is there a need for constants?
Is there a work around?
How can we use them global (without require('const')); ?
// Const
var constants = {
'PATH1' : __dirname + '/path..../',
'PATH2' : __dirname + '/path/..../'
};
module.exports = function(key) {
return constants[key];
};
//console.log(constants('PATH1'));
Would be glad if I get some feedback, like your thoughts about these questions.
I wish you a good day.
You don't need constants; simply don't attempt to use globals or constants in node.js
Doing what you want is as easy as:
// config.json
module.exports = {
somePath: "/foo",
anotherPath: "/foo/bar"
};
Use in a file
// a.js
var config = require("./config");
config.somePath; //=> "/foo"
Use in another file
// b.js
var config = require("./config");
config.anotherPath; //=> "/foo/bar"
Just recently, in another question, I went into depth about how it's completely unnecessary to use globals in node.js
This is a bad idea, but it can be done. I've only tested this in Node.js. It may or may not work in the browser. If you substitute global for window it might work reliably in the browser.
Here you go:
app.js:
Object.defineProperty(global, 'myConst', {
get: function() {
return 5;
}
})
myConst = 6
console.log(myConst) //5
Run like:
node app.js
Tested with v0.10.3.