“要求"后如何删除模块在 node.js 中? [英] How to remove module after "require" in node.js?

查看:19
本文介绍了“要求"后如何删除模块在 node.js 中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

比方说,在我需要一个模块并执行以下操作之后:

Let say, after I require a module and do something as below:

var b = require('./b.js');
--- do something with b ---

然后我想带走模块b(即清理缓存).我该怎么做?

Then I want to take away module b (i.e. clean up the cache). how I can do it?

原因是我想在不重新启动节点服务器的情况下动态加载/删除或更新模块.有什么想法吗?

The reason is that I want to dynamically load/ remove or update the module without restarting node server. any idea?

------- 更多--------根据建议删除require.cache,还是不行...

------- more -------- based on the suggestion to delete require.cache, it still doesn't work...

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 时,它仍然存在!它仍然可以访问.除非我这样做:

However, when i call b, it is still there! it is still accessible. unless I do that:

b = {};

不确定这是否是处理该问题的好方法.因为如果稍后,我再次 require ('./b.js') 而 b.js 已被修改.它需要旧的缓存 b.js(我试图删除它)还是新的?

not sure if it is a good way to handle that. because if later, I require ('./b.js') again while b.js has been modified. Will it require the old cached b.js (which I tried to delete), or the new one?

----------- 更多发现--------------

----------- More finding --------------

好的.我做了更多的测试和使用代码......这是我发现的:

ok. i do more testing and playing around with the code.. here is what I found:

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.

推荐答案

你可以用这个来删除它在缓存中的条目:

You can use this to delete its entry in the cache:

delete require.cache[require.resolve('./b.js')]

require.resolve() 会找出./b.js 的完整路径,用作缓存键.

require.resolve() will figure out the full path of ./b.js, which is used as a cache key.

这篇关于“要求"后如何删除模块在 node.js 中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆