Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/node.js/34.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 有状态单态模_Javascript_Node.js_Commonjs - Fatal编程技术网

Javascript 有状态单态模

Javascript 有状态单态模,javascript,node.js,commonjs,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]; }; }

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

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

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

该州是否能经受多次
要求
调用?或者应该使用一个简单的全局对象吗?

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

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
,您必须明确说明这一点。要删除缓存,它不会意外地被删除。下面是你必须要做的(不要这样做,我不明白为什么会有必要):酷,谢谢!所以在一个模块中缓存到RabbitMQ服务器的连接是可以的?是的。对于
require
,您必须明确说明这一点。要删除缓存,它不会意外地被删除。以下是你必须要做的事情(不要这样做,我不明白为什么有必要这样做):