简体   繁体   中英

Release required module from Node.js

How can one release a Node.js module during runtime in order to save memory or improve the overall performance.

My application dynamically loads modules in Node.js during runtime, but does not unload any of them. I'm looking for such functionality esp. to update a module that has been changed after the code loaded the module; and also to unload modules that may not be used further.

Any insights?

Thanks.

It sounds like you're creating some sort of plugin system. I would have a look at Node VM's: http://nodejs.org/docs/latest/api/vm.html

It allows you to load and run code in a sandbox which means when it's finished all it's internal allocations should be freed again.

It is marked as unstable, but that doesn't mean it doesn't work. It means the API might change in future versions of Node.

As an example, Haraka, a node based smtp server, uses the VM module to (re)load plugins.

To unload a script, you can do this:

delete require.cache['/your/script/absolute/path']    // delete the cache
var yourModule = require('/your/script/absolute/path') // load the module again

So if you have plugin modules, you can watch those files' change, then dynamically unload(delete the cache), then require that script again.

But make sure you are not leaking memory, you can re-assign the changed module to the old variable. Here is a handy tool that you can check the memory: node-memwatch .

Good luck!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM