javascript - 如何在不依赖其缓存系统的情况下在 NodeJS 中创建真正的单例

标签 javascript node.js

有时候确实需要单例,而Node的缓存系统并不可靠。甚至官方文档也提到了它:

Modules are cached based on their resolved filename. Since modules may resolve to a different filename based on the location of the calling module (loading from node_modules folders), it is not a guarantee that require('foo') will always return the exact same object, if it would resolve to different files.

来源:https://nodejs.org/api/modules.html#modules_module_caching_caveats


如何在不依赖 Node 缓存的情况下创建单例?有可能吗?

最佳答案

您误解了文档。这意味着如果您的文件结构是:

 /foo.js
 /bar.js
 /sub/foo.js
 /sub/bar.js

然后 require("foo")bar.js 文件中将导入不同的模块(/foo.js/sub/foo.js).

NodeJS 的缓存系统可靠。

关于javascript - 如何在不依赖其缓存系统的情况下在 NodeJS 中创建真正的单例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55847806/

相关文章:

javascript - 单击时聚焦于父元素不可用

javascript - 如何检查日期是否在 30 天内?

c++ - 带有 NodeJS 订阅者的 ZMQ 发布者服务器

node.js - nodejs express读取文件并异步返回响应

输出甲板平面图的 JavaScript

javascript - 编写代码来启用或禁用某些控件的最佳方法

javascript - 如何在路由更改时卸载组件

javascript - 在 node.js 模块中将原型(prototype)函数添加到 JSON

javascript - Angular POST 请求不起作用

javascript - 正则表达式如何捕获重复值而不捕获文本周围的空格