brandonscript
brandonscript

Reputation: 72885

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. I'm doing this right now:

In main.js (main entry point) I've got:

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?

Upvotes: 1

Views: 94

Answers (3)

Elyas74
Elyas74

Reputation: 548

You can do this :

global.debug = true ;// or false

//and in any file

if(global.debug){
   // something
}

Upvotes: 0

Johannes Reuter
Johannes Reuter

Reputation: 3547

Use a config-module and include it if needed:

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

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

Upvotes: -1

Daniel
Daniel

Reputation: 38771

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

Upvotes: 4

Related Questions