我想完全卸载节点模块。
这是用于节点插件系统的,该系统会自动加载一些模块。为了检查是否存在每个需要的属性,我加载和卸载了模块,因为我需要将其作为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
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的愚蠢函数。
答案 0 :(得分:0)
您从require.cache [moduleName]中删除了引用,但是对模块的引用在主脚本中仍以plugin
的形式存在。如果取消分配(plugin = null
),并且周围没有其他引用,那么最终应该将其回收。