如何在node.js中的“require”之后删除模块?

让我们说,在我需要一个模块,并做一些如下:

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

然后我想带走模块b(即清理缓存)。我怎么能做到呢?

原因是我想动态加载/删除或更新模块而不重新启动节点服务器。任何想法?

– – – – 更多 – – – –
基于删除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的完整路径,用作缓存键。

http://stackoverflow.com/questions/15666144/how-to-remove-module-after-require-in-node-js

本站文章除注明转载外,均为本站原创或编译
转载请明显位置注明出处:如何在node.js中的“require”之后删除模块?