3

I use node-cache in my expressed based application. It needs to be setup using the following code;

const NodeCache = require( "node-cache" );
const myCache = new NodeCache( { stdTTL: 100, checkperiod: 120 } );

After that it can be used like

myCache.get(key)

The problem I am having is that in the express setup I have the routes are dynamic and I cannot access the myCache constant declared in the index.js I read up on modules and understand they are cached and each new call that calls require gets the cached version.

To overcome my problem and be able to call the same object from any route I thought of using the following singleton-ish approach in my routes;

var nodeCache = require('node-cache');

if (!nodeCache.instance) {
    nodeCache.instance = new nodeCache({ stdTTL: 3600 });
}

nodeCache.instance.get('key');

This seems to work well, but I am pretty unsure about this setup, if this is something that is supposed to be done, or if there are better alternatives.

Estus Flask
  • 206,104
  • 70
  • 425
  • 565
Bastiaan
  • 686
  • 1
  • 8
  • 20

1 Answers1

3

CommonJS modules are evaluated on first import and are able to naturally provide singletons as exported values.

cache.js module can be:

var nodeCache = require('node-cache');

module.exports = new nodeCache({ stdTTL: 3600 });

Then the same node cache instance is imported from cache.js everywhere it's used.

Estus Flask
  • 206,104
  • 70
  • 425
  • 565
  • It will be created on first import. If it's imported the first time in index.js then yes, it's created there. The point is that `require('./cache.js') === require('./cache.js')`, so you're using the same instance everywhere. – Estus Flask Apr 13 '19 at 14:28
  • So I need to create an additional module that exports the 'instantiated' node-cache module? In my code I add the instance to the node-cache module itself, without the need of a separate module, is that not ok? – Bastiaan Apr 13 '19 at 14:29
  • Yes, you need to create a separate module. Adding `instance` is not ok because it's a hack that pollutes another module, you piggyback node-cache module instead of creating your own. As for Express, you can alternatively store app-wide values in settings table, https://expressjs.com/en/api.html#app.set – Estus Flask Apr 13 '19 at 14:33
  • makes perfect sense, will go for the separate module. Thanks! – Bastiaan Apr 13 '19 at 14:38
  • 2 years later, helped me too! – Gerry Jul 05 '21 at 01:13