node require.cache delete不会导致重新加载模块

时间:2016-06-11 08:22:35

标签: node.js caching npm require

我正在为我的npm模块编写测试。 这些测试需要安装npm模块的多个版本,以检查模块是否将其验证为兼容或不兼容。

不知何故,我在stackoverflow或npm数据库中找到的所有uncache库或函数都无效..

我使用辅助函数安装/卸载npm模块:

function _run_cmd(cmd, args) {
    return new Promise((res, rej) => {
        const child = spawn(cmd, args)
        let resp = ''
        child.stdout.on('data', function (buffer) {
            resp += buffer.toString()
        })
        child.stdout.on('end', function() {
            res(resp)
        })
        child.stdout.on('error', (err) => rej(err))
    })
}

global.helper = {
    npm: {
        install: function (module) {
            return _run_cmd('npm', ['install', module])
        },
        uninstall: function (module) {
            decacheModule(module)
            return _run_cmd('npm', ['uninstall', module])
        }
    }
}

这是我当前的decache函数,它应该清除所有模块缓存(我尝试过其他的,包括npm模块,它们都没有工作)

function decacheModules() {
    Object.keys(require.cache).forEach(function(key) {
        delete require.cache[key]
    })
}

我正在安装less模块​​的多个版本(https://www.npmjs.com/package/less

在我的第一个测试中,我正在安装一个没有render函数的弃用版本。

在其他一些测试中,我正在安装一个具有render功能的最新版本。不知何故,如果我测试该功能,测试确实失败了。 如果我跳过第一次测试,则另一次测试成功。 (render - 存在功能)。

这让我相信删除require.cache没有影响......

我使用的是节点v4.2.4。

1 个答案:

答案 0 :(得分:0)

如果有对旧模块的引用:

var less = require('less');

清除模块缓存不会导致该引用被清除并重新加载模块。 为了实现这一点,至少你不将模块存储到变量,在任何地方都使用“require('less')”。