How to solve module caching caveats in node.js (singleton issue)?

Following another question, I understand I am facing a module caching caveat issue. Obviously, several instances of the same module are created in my project.

I am requiring the module from other modules located in different folders:

var mm = require("./myModule.js");
...

var mm = require("../myDir/myModule.js");
...

var mm = require("../../MyDir/myModule.js");
...

I have been trying to create a unique instance of myModule (singleton) using an object and by exporting it:

var myModule = function() {

    if (!(this instanceof myModule)) { return new myModule(); }

    ...

};

...

module.exports = new myModule();

Yet, it does not solve the issue. What is the right way to declare a singleton in node.js? And how to retrieve the instance in other modules?

Upvotes: 1

Views: 531

Answers (2)

vkurchatkin
vkurchatkin

Reputation: 13570

It's a Windows issue: file paths in Windows are case insensitive, so ./File.txt and ./file.txt refer to the same file. The problem is, that node is not aware of that and uses resolved file paths as cache keys, so it's possible to load same module multiple times using different casing.

More about that issue and discussion: https://github.com/joyent/node/issues/6000

Solution (kind of): don't use upper case in file and directory names inside node projects

Upvotes: 3

AJcodez
AJcodez

Reputation: 34166

That pattern definitely works for a singleton.

// singleton.js

module.exports = new Singleton

function Singleton () {
  this.rand = Math.random()
}

// one.js

var singleton = require('./singleton')
console.log(singleton.rand)

// two.js

require('./one')
var singleton = require('./singleton')
console.log(singleton.rand)

Sure enough consistent output.

0.7851003650575876
0.7851003650575876

Upvotes: -2

Related Questions