在express / node中使用全局variables

试图find一个解决scheme,我发现了4个解决scheme,但我想知道哪一个更好/最好的做法。 为什么! :P

1.使用req.app.get()

// app.js app.set('settings', { domain: 'http://www.example.org' }); // other file console.log(req.app.get('settings')); 

2.使用req.app.settings(与上面类似)

 // app.js app.set('settings', { domain: 'http://www.example.org' }); // other file console.log(req.app.settings.settings); 

3.导出应用程序对象,所以我可以访问app.get()没有req对象

 // 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.使用全局variables。 可能是个坏主意,但是…不是“设置”是一个全球性的东西吗? (我可以避免重复使用,所以我没有得到范围问题)

 // app.js settings = { domain: 'http://www.example.org' }; // other file console.log(settings); 

简要意见:

1.使用req.app.get()

在这里,我们正在为全局属性定义访问器方法(getter / setter)。 所以它的语法正确,很容易理解。

2.使用req.app.settings(与上面类似)

在这里,我们正在定义setter,但不使用getter来访问值。 海事组织,不是一个好方法。 另外,它也很难理解。

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

3.导出应用程序对象,所以我可以访问app.get()没有req对象

为什么,如果你可以访问它,你需要导入一个文件。 如果你对app模块有很高的依赖性(比如你所需要的全局设置数量很高),这通常是构build应用程序时的情况。

4.使用全局variables。 可能是个坏主意,但是…不是“设置”是一个全球性的东西吗? (我可以避免重复使用,所以我没有得到范围问题)不是一个好方法,因为在这种情况下代码是不可维护的。

国际海事组织,优先事项是:1> 3> 2> 4。