你有一个有状态的Node.js模块吗?像:
exports.connectionsCache = new (function () {
var cache = {};
this.getOrCreate = function (url) {
if (!cache[url]) {
cache[url] = new Connection(url);
}
return cache[url];
};
}());
该州是否会在多个require
来电中存活?或者应该使用一个简单的全局对象?
答案 0 :(得分:5)
require
已缓存模块:
test2.js:
module.exports = {
state: 0
};
test.js
var state = require("./test2.js");
state.state = 3;
console.log(state.state);
var state2 = require("./test2.js");
console.log(state2.state);
state2.state = 4;
console.log(state.state);
输出
$ node test.js
3
3
4