0

Can you have a stateful Node.js module? Like:

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

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

Will the state survive multiple require calls? Or should one use a simple global object for that?

jcolebrand
  • 15,889
  • 12
  • 75
  • 121
katspaugh
  • 17,449
  • 11
  • 66
  • 103

1 Answers1

5

require already caches the module:

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);

Output

$ node test.js
3
3
4
Esailija
  • 138,174
  • 23
  • 272
  • 326
  • Cool, thanks! So it's OK to cache connections to RabbitMQ servers in a module? – katspaugh Aug 13 '12 at 15:59
  • 1
    Well, yeah. You'd have to be explicit about it for `require` to drop the cache, it doesn't accidentally get dropped. Here's what you would have to do (Don't though, I don't see why it would ever be necessary): http://stackoverflow.com/a/9210901/995876 – Esailija Aug 13 '12 at 16:00