Reputation: 178
I know using the global
variable is discouraged in node, but assuming I need to store some data globally, which is a worse approach:
using global
Using the require cache directly to store an object, i.e.
require.cache["myGlobalVar"] == {};
I suspect that option 2 is worse because the require cache is intended to be used for modules.
More details: I thought about using require("myLibrary").myGlobalVar but that would require having myLibrary accessible to all the files calling it, which might not be possible in practice. I'm making a code coverage tool so I can expect the user to install "myLibrary" in their dev/test modules, but not necessarily in their src node_modules directory, to which the instrumented code files would refer.
Upvotes: 6
Views: 13804
Reputation: 390
Every time, when you require cache file, it will trigger the function again and initialize the cache object again.
var cache = {}
to solve this we can implement the cache like mentioned below:
//cache.js
module.exports = {
cache: {},
get: function (key) { return this.cache[key]; },
set: function (key, val) { this.cache[key] = val; },
dumpCache: function () { return this.cache } // this just for testing purpose
}
// index.js
var cache = require('./cache');
cache.set('12', 'Hey');
console.log(cache.get('12'));
console.log(cache.dumpCache());
Upvotes: 1
Reputation: 2368
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.)
Upvotes: 13
Reputation: 25555
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'
Upvotes: 14