How to use global variable in node.js?

node.js

node.js Problem Overview


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 ?

node.js Solutions


Solution 1 - node.js

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);

Solution 2 - node.js

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.

Solution 3 - node.js

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

for e.g

global.underscore = require("underscore");

or

GLOBAL.underscore = require("underscore");

Solution 4 - node.js

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

Solution 5 - node.js

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.

Solution 6 - node.js

May be following is better to avoid the if statement:

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

Solution 7 - node.js

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionBdfyView Question on Stackoverflow
Solution 1 - node.jsPickelsView Answer on Stackoverflow
Solution 2 - node.jsSean H. WorthingtonView Answer on Stackoverflow
Solution 3 - node.jsShubham GautamView Answer on Stackoverflow
Solution 4 - node.jsDoron SegalView Answer on Stackoverflow
Solution 5 - node.jsRaz BuchnikView Answer on Stackoverflow
Solution 6 - node.jsSushant AgrawalView Answer on Stackoverflow
Solution 7 - node.jsKazuya GoshoView Answer on Stackoverflow