6

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?

Community
  • 1
  • 1
hguser
  • 35,079
  • 54
  • 159
  • 293
  • 1
    The link you've included says that the module cache will always work. The module will NOT be invalidated and reloaded. It should work just fine to do what you want just like you planned. – jfriend00 Nov 12 '14 at 03:02
  • 1
    Ok, misunderstand it since I read the "...may not cause..."... – hguser Nov 12 '14 at 03:10

1 Answers1

4

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.

mscdex
  • 104,356
  • 15
  • 192
  • 153