node.js - Node 是否需要收集缓存垃圾?

标签 node.js

NodeJS require 函数,加载模块,有一个“缓存”(它是一个对象)。

一旦我不再使用该模块,这个缓存的条目是否被垃圾收集? (如果再次使用会导致从磁盘加载)

我认为答案是“否”,但我没有在网上找到任何引用资料

最佳答案

Entries is this cache are garbage collected once I'm no longer using the module?

没有。使用 require() 加载的模块会无限期缓存,无论您是否使用完它们。

模块使用的 Javascript 变量/对象的内存是垃圾收集的,遵守垃圾收集的所有正常规则(当没有仍然引用变量/对象的实时代码时)。但是,模块缓存保留对加载模块本身的引用,因此代码或任何模块级变量不会被垃圾收集,除非手动从缓存中删除模块。

这是一个 link to the node.js doc关于这个话题。

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.

如果您想从缓存中手动删除模块,请在此处进行描述:

unloading code/modules

不过,鉴于 node.js 的结构方式,这将允许对所有模块级变量进行垃圾回收,我认为它实际上不会从内存中卸载代码。

关于node.js - Node 是否需要收集缓存垃圾?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37620697/

相关文章:

javascript - agent.add 在 Promise.then 对话框流中不起作用

node.js - 解构 Sequelize 查询

mysql - 连接 mySQL 和 Nodejs

node.js - 如何打开控制台与 Express 应用交互?

javascript - 如何通过文件加载器加载图像作为多个页面的背景图像

javascript - 查找将 $lt 和 $gt 与 javascript 日期一起使用

javascript - setTimeout 阻止事件循环

node.js - 如何在node js中使用多个内容发送邮件?

javascript - Nodejs 中 undefined variable 无法显示错误

node.js - 从控制台删除 Sockjs 调试信息? ( Node )