[node.js] How to use global variable in 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 ?

This question is related to node.js

The answer is


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.


May be following is better to avoid the if statement:

global.logger || (global.logger = require('my_logger'));

If your app is written in TypeScript, try

(global as any).logger = // ...

or

Object.assign(global, { logger: // ... })

However, I will do it only when React Native's __DEV__ in testing environment.


Global variables can be used in Node when used wisely.

Declaration of global variables in Node:

a = 10;
GLOBAL.a = 10;
global.a = 10;

All of the above commands the same actions with different syntaxes.

Use global variables when they are not about to be changed

Here an example of something that can happen when using global variables:

// app.js
a = 10; // no var or let or const means global

// users.js
app.get("/users", (req, res, next) => {
   res.send(a); // 10;
});

// permissions.js
app.get("/permissions", (req, res, next) => {
   a = 11; // notice that there is no previous declaration of a in the permissions.js, means we looking for the global instance of a.
   res.send(a); // 11;
});

Explained:

Run users route first and receive 10;

Then run permissions route and receive 11;

Then run again the users route and receive 11 as well instead of 10;

Global variables can be overtaken!

Now think about using express and assignin res object as global.. And you end up with async error become corrupt and server is shuts down.

When to use global vars?

As I said - when var is not about to be changed. Anyways it's more recommended that you will be using the process.env object from the config file.


you can define it with using global or GLOBAL, nodejs supports both.

for e.g

global.underscore = require("underscore");

or

GLOBAL.underscore = require("underscore");

I would suggest everytime when using global check if the variable is already define by simply check

if (!global.logger){
  global.logger = require('my_logger');
}

I've found it to have better performance