Release the required module from Node.js

How can I free the Node.js module at run time to save memory or improve overall performance?

My application dynamically loads modules into Node.js at runtime, but does not unload them. I am looking for such esp functionality. update the module that was changed after the module loaded the code; as well as for unloading modules that cannot be used further.

Any ideas?

Thanks.

+4
source share
2 answers

It looks like you are creating some kind of plugin system. I would look at Node VM: http://nodejs.org/docs/latest/api/vm.html

It allows you to download and run code in the sandbox, which means that when it has finished all its internal selections must be freed again.

It is marked as unstable, but this does not mean that it does not work. This means that the API may change in future versions of Node.

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

+2
source

To offload the 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 observe the changes in these files, then dynamically upload (delete the cache), and then request the script again.

But make sure you don't skip memory; you can reassign the changed module to an old variable. Here is a handy tool that you can check in memory: node-memwatch .

Good luck

+1
source

Source: https://habr.com/ru/post/1491696/


All Articles