Release required module from Node.js

后端 未结 2 1220
梦毁少年i
梦毁少年i 2020-12-19 17:33

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 d

相关标签:
2条回答
  • 2020-12-19 17:49

    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.

    0 讨论(0)
  • 2020-12-19 18:12

    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!

    0 讨论(0)
提交回复
热议问题