6

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);
1
  • If I were to rate, 1, 2, 3, 4. Don't do 4 at all. Commented Mar 23, 2014 at 3:27

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

I like 1 also, but you need a "req" object. Let's say you require a paginate.js in your routes. In your routes you have "req", but not in "paginate.js". so you end doing require('paginate')(req) ? Sounds bad to me...
thats what i mentioned. Its depend upon your requirement. As i mentioned, you can go with 3 if you have dependency of app module.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.