【问题标题】:Stateful singleton modules有状态的单例模块
【发布时间】:2012-08-13 15:51:44
【问题描述】:

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

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

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

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

【问题讨论】:

    标签: javascript node.js commonjs


    【解决方案1】:

    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
    

    【讨论】:

    • 酷,谢谢!那么在一个模块中缓存到 RabbitMQ 服务器的连接就可以了吗?
    • 嗯,是的。您必须明确说明require 才能删除缓存,它不会意外被删除。这就是你必须做的事情(虽然不要,我不明白为什么它是必要的):stackoverflow.com/a/9210901/995876
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-19
    • 2019-09-22
    • 2012-01-04
    • 1970-01-01
    相关资源
    最近更新 更多