有状态单例模块

时间:2012-08-13 15:51:44

标签: javascript node.js commonjs

你有一个有状态的Node.js模块吗?像:

exports.connectionsCache = new (function () {
    var cache = {};

    this.getOrCreate = function (url) {
        if (!cache[url]) {
            cache[url] = new Connection(url);
        }
        return cache[url];
    };
}());

该州是否会在多个require来电中存活?或者应该使用一个简单的全局对象?

1 个答案:

答案 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