alditis
alditis

Reputation: 4817

Nodejs and Expressjs: Constants in global variable

Defined in: util/constant.js

module.exports = {
    userTypeAdmin: 0,
    userTypeUser: 1
};

Required only once in: app.js

...
global.constant = require('./util/constant');
...

Used many times

In: route/index.js

console.log(constant.userTypeAdmin); // Show 0

In: route/user.js

console.log(constant.userTypeUser); // Show 1

Question:

I must removed of app.js: global.constant = require('./util/constant');

and add: const constant = require('../util/constant');

in route/index.js and route/user.js ? Or that's ok how I am it making?

Upvotes: 1

Views: 3445

Answers (1)

RIYAJ KHAN
RIYAJ KHAN

Reputation: 15292

1.    const constant = require('../util/constant');
2.    global.constant = require('./util/constant');

Only difference in these,

statement 1 ask you to import the constant package wherever you want to use it.

statement 2 make available constant package globally.so,you can access it without import.

With statement 2,if you modified any properties within constant,it will reflect throughout the application.

So,make sure,you are using global only when you want to share something across the application.

If you want to share the data globally,and don't want this should be change,then delcare each primitive variable with const keyword.In this case,making object const will not help you. In either case you can exclude it.

Upvotes: 2

Related Questions