Alex Seville Alex Seville - 4 months ago 33
Node.js Question

Global variable vs. require.cache in NodeJS

I know using the

variable is discouraged in node, but assuming I need to store some data globally, which is a worse approach:

  1. using global

  2. 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.


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'