javascript - Node.js 如何使用 require() 处理多次包含的大数组和对象?

标签 javascript node.js caching

在我的项目中,我间接使用了一些大数据数组 - 在我的具体情况下,这些是 Minecraft block 和项目信息。

正如我所说,我正在间接使用数据 - 我的一个依赖项使用它。但现在我也想使用它,这意味着我需要 require() 包含所有数据的 .js 文件。由于 javascript 中没有常量,并且加载的对象是可变的,我的问题是它是否真的会在 Node 的内存中加载两次。如果是,我该怎么做才能节省内存?

最佳答案

https://nodejs.org/docs/latest/api/modules.html#modules_caching

Modules are cached after the first time they are loaded. This means (among other things) that every call to require('foo') will get exactly the same object returned, if it would resolve to the same file.

因此,如果您的依赖项位于项目内部,并且它require与您想要require相同的文件 - 它将返回同一个对象。但是,如果您的依赖项 A 是一个 Node 模块,需要依赖项 B(大数组)作为单独的 Node 模块...并且您将 B 添加为整个项目的依赖项,它将解析为不同的文件。这意味着它将是一个不同的对象。

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.

关于javascript - Node.js 如何使用 require() 处理多次包含的大数组和对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31741904/

相关文章:

javascript - 如何在reactjs中重建现有的Dom?

javascript - Node.js 无法处理多个 tcp 消息

javascript - Vue CLI 和服务器端渲染

python - 无法让 nginx 缓存 uwsgi 结果

Python 2.7 ImportMismatchError 在 basedir 重命名后由过时的 pycache 引起

javascript - mocha with nodejs assert 挂起/超时为 assert(false) 而不是错误

javascript - 从复杂字符串数组创建 JSON 对象

javascript - `f()` 和 `new f()` 有什么区别?

mysql - Passport Node (错误 : Failed to deserialize user out of session.)

java - 为什么我的 Java 应用程序仅获取旧版本的在线文件?