所需模块相同,path不同,variables不共享

我真的失去了如何工作,我试图find真相。 Nodejs文档说,每次你需要相同的模块(不同的path或不同),你会得到相同的对象。 但对我来说,即使我需要相同的模块,这也不是同一个对象。

我已经创build了一个简单的项目来尝试这个,一个内存caching系统。 首先我们有主文件,第一个testing文件添加一个项目,第二个testing文件获取添加项目。

 //main.js var exports = module.exports = {}; var debug = require("debug")("memcache:main"); var CACHE = {}; debug(CACHE); exports.set = addItem; exports.get = getItem; function addItem(key, value) { debug(key); debug(value); CACHE[ key ] = value; debug(CACHE[ key ]); } } function getItem(key) { debug(key); debug(CACHE[ key ]); return CACHE[ key ]; } 

第一个testing文件添加一个项目

 //test/test1.js var memcache = require("../main"); memcache.set("id1", { name: "lola" }); 

第二个testing文件检索添加的项目

 // test/child/test2.js var memcache = require("../../main"); setInterval( function () { console.log(memcache.get("id1")); }, 3000 ); 

现在这是控制台输出

 MacBook-Pro:memcache fluxb0x$ DEBUG=memcache:* node test/test1.js memcache:main {} +0ms memcache:main id1 +3ms memcache:main { name: 'lola' } +0ms memcache:main undefined +1ms memcache:main { name: 'lola' } +0ms MacBook-Pro:memcache fluxb0x$ DEBUG=memcache:* node test/child/test2.js memcache:main {} +0ms memcache:main id1 +3s memcache:main undefined +0ms undefined memcache:main id1 +3s memcache:main undefined +0ms undefined memcache:main id1 +3s memcache:main undefined +1ms undefined memcache:main id1 +3s memcache:main undefined +0ms undefined memcache:main id1 +3s memcache:main undefined +0ms undefined memcache:main id1 +3s memcache:main undefined +0ms undefined 

任何build议如何我需要不同的path相同的模块,仍然有相同的variables?

谢谢。

您的caching不是真正的内存caching,它只是一个持有值的对象。 所以它在两个节点的执行过程中并不持久。 这可以通过对代码进行小的更改来certificate。

更改testing2文件以显示testing方法

 // test/child/test2.js var memcache = require("../../main"); exports.test = function(){ setInterval( function () { console.log(memcache.get("id1")); }, 3000 ); } 

将值添加到caching后,在test1中使用暴露的testing方法。

 //test/test1.js var memcache = require("../main"); var test2 = require("./child/test2"); memcache.set("id1", { name: "lola" }); test2.test(); 

然后像你一样运行test1。

$ DEBUG=memcache:* node test/test1.js

这会给你预期的结果。