Félix Sanz
Félix Sanz

Reputation: 1892

Using global variables in express / node

Trying to find a solution, i found 4 solutions, but i would like to know which one is better / best practice. And why! :P

1. Using req.app.get()

// app.js

app.set('settings', { domain: 'http://www.example.org' });

// other file

console.log(req.app.get('settings'));

2. Using req.app.settings (similar to above)

// app.js

app.set('settings', { domain: 'http://www.example.org' });

// other file

console.log(req.app.settings.settings);

3. Exporting app object so i can access app.get() without req object

// app.js

app.set('settings', { domain: 'http://www.example.org' });
module.exports = app;

// other file

var app = require('../app');
console.log(app.get('settings'));

4. Using a global variable. Probably bad idea but... isn't "settings" a global thing anyway? (I can avoid reusing it so i dont get scope problems)

// app.js

settings = { domain: 'http://www.example.org' };

// other file

console.log(settings);

Upvotes: 6

Views: 11862

Answers (1)

Mohit Pandey
Mohit Pandey

Reputation: 3843

Brief opinion:

1. Using req.app.get()

Here, we are defining accessor method (getter/setter) for global properties. So its syntactically correct and quite easy to understand.

2. Using req.app.settings (similar to above)

Here, we are defining setter, but not using getter to access value. IMO, not a good way. Also, its difficult to understand as well.

console.log(req.app.settings.settings);

3. Exporting app object so i can access app.get() without req object

Why, you need to import a file, if you can access it. It may be useful if you have a high dependency of app module(like,high number of global setting which you need), which is generally the case when building an application.

4. Using a global variable. Probably bad idea but... isn't "settings" a global thing anyway? (I can avoid reusing it so i dont get scope problems) Not a good approach, as code is not maintainable in this case.

IMO, priority is like: 1 > 3 > 2 > 4.

Upvotes: 2

Related Questions