【发布时间】: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