作者热门文章
- mongodb - 在 MongoDB mapreduce 中,如何展平值对象?
- javascript - 对象传播与 Object.assign
- html - 输入类型 ="submit"Vs 按钮标签它们可以互换吗?
- sql - 使用 MongoDB 而不是 MS SQL Server 的优缺点
假设我需要一个模块并执行以下操作:
var b = require('./b.js');
--- do something with b ---
然后我想带走模块 b(即清理缓存)。我该怎么做?
原因是我想在不重新启动 Node 服务器的情况下动态加载/删除或更新模块。有什么想法吗?
------- 更多 --------根据删除require.cache的建议,还是不行……
what I did are few things:
1) delete require.cache[require.resolve('./b.js')];
2) loop for every require.cache's children and remove any child who is b.js
3) delete b
但是,当我调用 b 时,它仍然存在!它仍然可以访问。除非我这样做:
b = {};
不确定这是否是处理该问题的好方法。因为如果以后,我需要 ('./b.js') 在 b.js 已被修改时再次。它需要旧的缓存 b.js(我试图删除)还是新的?
-----------更多发现--------------
好的。我做了更多的测试和代码玩弄..这是我发现的:
1) delete require.cache[] is essential. Only if it is deleted,
then the next time I load a new b.js will take effect.
2) looping through require.cache[] and delete any entry in the
children with the full filename of b.js doesn't take any effect. i.e.
u can delete or leave it. However, I'm unsure if there is any side
effect. I think it is a good idea to keep it clean and delete it if
there is no performance impact.
3) of course, assign b={} doesn't really necessary, but i think it is
useful to also keep it clean.
最佳答案
您可以使用它来删除它在缓存中的条目:
delete require.cache[require.resolve('./b.js')]
require.resolve()
会计算出./b.js
的完整路径,用作缓存键。
关于node.js - 如何在 node.js 中删除 "require"之后的模块?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15666144/
我是一名优秀的程序员,十分优秀!