Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use global variable in node.js?

Tags:

node.js

For example I want to use custom logger:

logger = require('basic-logger'), logger.setLevel('info')  var customConfig = { showMillis: true, showTimestamp: true }  var log = new logger(customConfig) 

How to use this logger in other modules instead of console.log ?

like image 420
Bdfy Avatar asked Jun 11 '12 20:06

Bdfy


People also ask

What is global variable in NodeJS?

Global variables are variables that can be declared with a value, and which can be accessed anywhere in a program. The scope of global variables is not limited to the function scope or any particular JavaScript file. It can be declared at one place and then used in multiple places.

Why global variables are bad NodeJS?

Global variables are considered an anti-pattern in almost any programming language because they make it very hard to follow and debug code. When you browse the code, you never know which function sets or uses a global variable.

How do you set a global variable?

The global Keyword Normally, when you create a variable inside a function, that variable is local, and can only be used inside that function. To create a global variable inside a function, you can use the global keyword.


2 Answers

Most people advise against using global variables. If you want the same logger class in different modules you can do this

logger.js

  module.exports = new logger(customConfig); 

foobar.js

  var logger = require('./logger');   logger('barfoo'); 

If you do want a global variable you can do:

global.logger = new logger(customConfig); 
like image 117
Pickels Avatar answered Sep 18 '22 19:09

Pickels


global.myNumber; //Delclaration of the global variable - undefined global.myNumber = 5; //Global variable initialized to value 5.  var myNumberSquared = global.myNumber * global.myNumber; //Using the global variable.  

Node.js is different from client Side JavaScript when it comes to global variables. Just because you use the word var at the top of your Node.js script does not mean the variable will be accessible by all objects you require such as your 'basic-logger' .

To make something global just put the word global and a dot in front of the variable's name. So if I want company_id to be global I call it global.company_id. But be careful, global.company_id and company_id are the same thing so don't name global variable the same thing as any other variable in any other script - any other script that will be running on your server or any other place within the same code.

like image 28
Sean H. Worthington Avatar answered Sep 21 '22 19:09

Sean H. Worthington