javascript – Correctly create constants with mean.js (node ​​js)

Question:

I'm starting to study mean.js and I was in doubt as to the best way to create my application constants. I need to store some constants in the project to be accessible in various parts of the code.

Searching, I didn't find anything referring to constants in the documentation of mean.js itself… On the web, I found these references right here on stackoverflow.

https://stackoverflow.com/questions/15881665/how-to-define-a-constant-and-access-it-everywhere-in-nodejs

https://stackoverflow.com/questions/8595509/how-do-you-share-constants-in-nodejs-modules

Specifically on the second link I found Dominic Barnes' answer very elegant, but in the specific case of mean.js there is still a module abstraction to consider (mongoose).

How could I create my constants without interfering with the functioning of mongoose (and without getting ugly, preferably =) )

Note: one thing I would like is that each module file kept its own constants, so a Car model, for example, would have the constant

Cars.CARRO_DE_SEIO

That could have a string, object etc (I'd be fine with a string hehe). Something like this…

Answer:

In NodeJS there is a global which is a global variable. Just like window in javascript in browser.

So it's possible to add properties to global and use them wherever you want. It is however convenient to use for example global.minhasConstantes = {}; and in that object add key-value for each constant, not add new constants directly global.constanteA = 'foo'; global.constanteB = 'bar'; as a matter of good practice.

However what I usually do is define the variables when I call the modules. Examples:

in index.js

var modulo = require('modulo')(minhaConstante);

and in the module:

module.exports = function(k){
    return function(){
       // aqui fica o códigoque precisa da constante "k" que é passada para o escopo da função
    }
}

or just:

module.exports = function(k, outroParametro){
   // aqui fica o códigoque precisa da constante "k" que é passada para o escopo da função
}
Scroll to Top