Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a application level cache object in nodejs

I am using NodeJS by express framework, now I want to use the memory cache to save objects(almost 3000).

I have thought create a file like

cache.js:

var cache={};
module.exports=cache;

Then in any module I need the cache I can require it:

require('cache')
cache.xx=xxx

However it seems that I can not make sure that the cache object will be create and will be only one copy during the app running. Since the require may use the module cache or not.(from this link:https://stackoverflow.com/a/9210901/306719)

Any suggestion?

like image 362
hguser Avatar asked Nov 12 '14 02:11

hguser


1 Answers

That will work just fine. Node caches the module the first time it's loaded, so any additional requires will get the same exported object.

like image 67
mscdex Avatar answered Sep 20 '22 12:09

mscdex