My nodejs project requires memory tables accessible by different .js module. Some modules will update the tables but the data must be the same across all modules(sort of a in memory db). As such, I need a truly global object....not a global per module object. Creating a common.js file with all the objects then require it in all the modules will not do since the data will be global/local to the respective modules. I have seen reference to nodejs globals where global.myobject would be global to all modules but the documentation is not clear as to whether this is so or not. The last discussion I saw was from 2014. Can anyone update me on what is the current situation? How is this problem solved?
1 Answer
In node.js..
if you had a module called common.js, that looked like this..
'use strict';
var obj = {};
module.exports = obj;
And then inside another module you did this
'use strict';
var c = require('./common');
c.test = 1234;
Then later another module did this..
'use strict';
var c = require('./common');
console.log(c);
//output = { test: 1234 }
A module in modejs, is just another object. nodejs, caches any requires, and so will always return the same object.
One gotcha for windows users, windows filenames are not case-sensitive, so if you did require('Common'), and then did require('common'); you would have 2 version of the same module. And this is a good reason to keep all modules names in lowercase.
2 Comments
MichaelE
Thanks for the examples...the comments in stackoverflow.com/questions/4140661/… speaks to global.myobject do you have any comments on this alternative
Keith
The problem with global.myobject, is that of scope. The advantage of using a common.js file would be it's a global that's scoped to your modules's.. If for some reason there were other third party library's that wanted to share info, then the global.myobject could maybe be used. IOW: The global is a bit like browsers window object.
common.jsfrom the other modules will do. Every module is instantiated only once, regardless how often it is required. It's exactly what you need - a singleton.