Release required module from Node.js

后端 未结 2 1228
梦毁少年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 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!

提交回复
热议问题