johni07 johni07 - 3 months ago 51
Node.js Question

NodeJs define global constants

im wondering how to define global constants in node js.

My approach so far:

constants.js:

module.exports = Object.freeze({
MY_CONST: 'const one'});


controller.js:

var const = require(./common/constants/constants.js);
console.log(const.MY_CONST) ==> const one
const.MY_CONST ='something'
console.log(const.MY_CONST) ==> const one


Ok thats fine so far. But then i wanted to structure my constants like this:

constants.js:

module.exports = Object.freeze({
MY_TOPIC: {
MY_CONST: 'const one'
}
});


controller.js:

var const = require(./common/constants/constants.js);
console.log(const.MY_TOPIC.MY_CONST) ==> const one
const.MY_TOPIC.MY_CONST ='something'
console.log(const.MY_TOPIC.MY_CONST) ==> something


Hmm no MY_CONST is not constant any more...
How can i solve this problem?

Answer

You need to freeze inner object too. Something like that

module.exports = Object.freeze({
    MY_TOPIC: Object.freeze({
        MY_CONST: 'const one'
    })
});

Demo

var consts = Object.freeze({
  MY_TOPIC: Object.freeze({
    MY_CONST: 'const one'
  })
});

console.log(consts.MY_TOPIC.MY_CONST);
consts.MY_TOPIC.MY_CONST = "something";
console.log(consts.MY_TOPIC.MY_CONST);