节点模块已卸载但仍可访问

Node-module unloaded but still accessible

我想完全卸载节点模块。

这是用于自动加载一些模块的节点插件系统。为了检查是否每个需要的 属性 都存在,我加载和卸载模块,因为我需要 运行 它作为 child_process (解锁我的主应用程序)。我找到了一些朝这个方向发展的答案,但 none 对我有用。

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];
      }
    }
  }
}

执行此卸载后,我仍然可以调用 plugin.func1() - 一个返回 1 的愚蠢函数。

您从 require.cache[moduleName] 中删除了引用,但对模块的引用仍然作为 plugin 存在于您的主脚本中。如果您取消分配它 (plugin = null),并且周围没有其他引用,它最终应该被垃圾回收。