这里有三个文件。 Cacheobj导出File1和File2使用的缓存对象Obj。我想在两个文件之间同步缓存对象,即如果file1设置了键值,file2应该能够同步该值。
'cacheObj.js'
var cache = require('memory-cache');
module.exports =new cache.Cache();
'File1.js'
var cache =require('./cacheObj');
cache.put('key','val');
console.log(cache.get('key')); //output:val
'File2.js'
var cache=require('./cacheObj');
console.log(cache.get('key')); //output : null
答案 0 :(得分:0)
将您的Cache
导出为IIFE,应该没问题:
var Cache = (function () {
this.storage = []; // or probably ES6 Map since it is native key:value pairs
return this;
})();
module.exports = Cache;
之所以可行,是因为node
仅会调用一次缓存,即使required
在多个文件中也是如此。
您实际上通过module.exports = new cache.Cache()
导出了新实例,这与您要执行的操作相反。
在您的情况下,请尝试以下操作:
var cache = require('memory-cache');
var Cache = (function () {
this.storage = new cache.Cache();
return this;
})();
module.exports = Cache