Global variable vs. require.cache in NodeJS
Why don't you just create an in memory cache that all of your other code can then reference?
var memoryCache = module.exports = function () {
var cache = {};
return {
get: function (key) { return cache[key]; },
set: function (key, val) { cache[key] = val; }
}
}
You can then use the cache from any place by require'ing it.
var cache = require('../cache/memoryCache')();
cache.set('1234', 'value I want to share');
cache.get('1234'); // 'value I want to share'
The answer from Bill didn't work for me because it can in fact not be used "from any place by require'ing it". This is because it's exporting a function that is called on each require and thus creating a blank new (empty) cache each time.
The solution is exporting an instance of the function...
// cache/memoryCache.js
module.exports = function () {
var cache = {};
return {
get: function (key) { return cache[key]; },
set: function (key, val) { cache[key] = val; }
}
}();
...and then requiring that very instance each time.
// some other file
var cache = require('../cache/memoryCache');
cache.set('1234', 'value I want to share');
cache.get('1234'); // 'value I want to share'
(Note the difference: the pair of parenthesis "()" is now at the end of the function definition in the module and not after the require.)