有时候确实需要单例,而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/