Search code examples
node.jsnode-modulesrequire

Node-module unloaded but still accessible


I want to unload a node-module completely.

This is for node plugin system which automatically loads some modules. To check if every needed property is present I load and unload the module, as I need to run it as a child_process (to unblock my main application). I found some answers leading in this direction, but none of it worked for me.

loader.js

const pluginPath = "./path-to-my/index.js";
const plugin = require(path.resolve(pluginPath));

// Performing my testing 

// delete require.cache[pluginPath]; // first try
unloader()(path.resolve(pluginPath)); // does the same but to child modules too 
// see unloader.js

unloader.js

module.exports = () => {
  const d = [];
  const isDone = m => (d.indexOf(m) !== -1);
  const done = m => d.push(m);

  return (name) => {
    let resolvedName = require.resolve(name);

    if ((!isDone(resolvedName) && !isDone(name))) {
      let nodeModule = require.cache[resolvedName];

      done(resolvedName);
      done(name); 
      if (nodeModule) {
        for (let i = 0; i < nodeModule.children.length; i++) {
          let child = nodeModule.children[i];
          deleteModule(child.filename);
        }
        delete require.cache[resolvedName];
      }
    }
  }
}

after performing this unloading I am still able to call plugin.func1() -a stupid function returning 1.


Solution

  • You delete the reference from require.cache[moduleName], but the reference to the module still exists as plugin in your main script. If you unassign it (plugin = null), and there are no other references hanging around, it should eventually be garbage collected.