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.