a blog for those who code

Monday 30 May 2016

How to Store Global Objects in Node.js

In this post we will be discussing about storing global objects in Node.js. The most common advice which you will get is to "declare the variable without var" or "add the variable to the global object" or "add the variable to the GLOBAL object". In one of our previous posts we have discussed about the Globals in Node.js.

Global Objects in Node.js


To know more about global object in Node.js, type global in Node.js REPL you will get something like below where you will able to see the full structure of the global object.


Now we are going to play around with the global object in Node.js REPL as shown below.


As you can see that global and GLOBAL is almost the same thing. Actually we can say that GLOBAL is an alias of global. One more thing to note from above is that a variable declared with or without var is being attached to global object. This is because global object is shared among modules and the variable declared with var is only accessible to that particular module whereas variable declared without var is accessible to all modules.

So now you can say that "declare the variable without var" or "add the variable to the global object" or "add the variable to the GLOBAL object" are all the same thing.

Best way to store Global Objects

Using above approach is not recommended because they will be nightmare to maintain and usage will be difficult. Lets say you have a global name whereas you also have a local name with the same variable name, thus both will be attached to the global object thus making it very difficult to differentiate.

To overcome this challenge the best way to store global objects is to do module.exports to export all the global variables. You can create a local module which will manage the data for you and then you can use require() whenever you want to access the data. require() will cache the data thus in subsequent call you will get the same module every time thus maintaining the proper dependency management.

You can create a file called globalData.js whose contents will be :

var dataA = "valueA";
var dataB = "valueB";

module.exports = dataA;
module.exports = dataB;

This in other files you can use the require() method to call this local globalData module as shown below :

var globalData = require('./globalData.js');
var dataAValue = globalData.dataA;

One thing to note here that globally access data in node.js is shared by all requests from all users. So if you want to have different global varaiable for different logged in user you need to use express-session module .

Please Like and Share the CodingDefined Blog, if you find it interesting and helpful.

No comments:

Post a Comment