【问题标题】:Node-module unloaded but still accessible节点模块已卸载但仍可访问
【发布时间】:2019-10-30 06:59:28
【问题描述】:

我想完全卸载一个节点模块。

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

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

卸载程序.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 的愚蠢函数。

【问题讨论】:

    标签: node.js node-modules require


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 2020-08-23
      • 2015-09-23
      • 2018-07-22
      • 2020-01-24
      • 1970-01-01
      • 1970-01-01
      • 2020-04-18
      • 1970-01-01
      • 2019-10-17
      相关资源
      最近更新 更多