rob rob - 1 year ago 105
Node.js Question

unloading code/modules

I'm curious if there is any good way to unload a module after using it. I have some cases where I need to use modules that bring in a lot of code, but they are used rarely (say as an admin tool), but I hesitate to use them because afterwards they'll presumably just waste memory that could be better used elsewhere. Is there any way to unload them, either explicitly or by allowing the system to do so when they haven't been used for a while?

Answer Source

Yes, it is possible to access the module cache directly:

var name = require.resolve('moduleName');
delete require.cache[name];

Note that if your code carries a reference to whatever was exposed by these modules you want to get rid of, it won't be cleaned up.

(As an aside: Underneath the surface, require.resolve and require.cache are just proxies to Module._resolveFilename and Module._cache respectively, with Module being the core module loader, i.e. require('module').)