简体   繁体   English

如何解决node.js中的模块缓存警告(单个问题)?

[英]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: 我一直在尝试使用对象并通过将其导出来创建myModule (singleton)的唯一实例:

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? 在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. 这是Windows的问题:Windows中的文件路径不区分大小写,因此./File.txt./file.txt引用相同的文件。 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 有关该问题和讨论的更多信息: 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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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