在Node.js中使用“全局”
在我正在构build的Node API中,我想要一个创build全局布尔的快捷方式来启用(或禁用)一些debugging日志logging。 我现在正在这样做:
在main.js
(主要入口点)我有:
global.DEBUG = true;
然后在我使用的任何模块中,我可以这样做:
if (DEBUG) { // then do stuff }
这样做有什么不妥吗? 有没有更合适的方法,如果是的话,为什么这是更好的方法?
你最好用环境variables来做这件事。
var DEBUG = process.env.DEBUG; if (DEBUG) { // then do stuff }
然后启动你的应用程序
$ DEBUG=TRUE node app.js
你可以这样做 :
global.debug = true ;// or false //and in any file if(global.debug){ // something }
使用一个configuration模块,并在需要时包含它:
//conf.js module.exports = { DEBUG: true } //other.js if(require('./conf').DEBUG)