简体   繁体   中英

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?

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM