0

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

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

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

国家会在多次require通话中幸存下来吗?还是应该为此使用一个简单的全局对象?

4

1 回答 1

5

require已经缓存了模块:

test2.js:

module.exports = {
    state: 0
};

测试.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
于 2012-08-13T15:55:49.723 回答