简体   繁体   English

在Node.js中使用“global”

[英]Using “global” in Node.js

In a Node API I'm building I want a quick and dirty way of creating a global bool to enable (or disable) some debug logging. 在我正在构建的Node API中,我想要一种创建全局bool的快速而肮脏的方式来启用(或禁用)某些调试日志记录。 I'm doing this right now: 我现在正在这样做:

In main.js (main entry point) I've got: main.js (主要入口点),我得到了:

global.DEBUG = true;

And then in any modules I use, I can do: 然后在我使用的任何模块中,我可以这样做:

if (DEBUG) { 
    // then do stuff 
}

Is there anything wrong with doing it this way? 这样做有什么不对吗? Is there a more appropriate way and if so, why is it a better way? 是否有更合适的方式,如果有,为什么它是更好的方式?

You're better off doing this with environment variables. 你最好用环境变量来做这件事。

var DEBUG = process.env.DEBUG;
if (DEBUG) {
  // then do stuff
}

Then start your app 然后启动你的应用程序

$ DEBUG=TRUE node app.js

You can do this : 你可以这样做 :

global.debug = true ;// or false

//and in any file

if(global.debug){
   // something
}

Use a config-module and include it if needed: 使用配置模块并在需要时包含它:

//conf.js
module.exports = {
DEBUG: true
}

//other.js
if(require('./conf').DEBUG)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM