在node.js文档中:
模块在第一次加载后被缓存。这意味着(除其他外)每次调用require('foo')都会得到完全相同的返回对象,如果它将解析到相同的文件。
是否有一种方法使这个缓存无效?例如,对于单元测试,我希望每个测试都在一个新鲜的对象上工作。
在node.js文档中:
模块在第一次加载后被缓存。这意味着(除其他外)每次调用require('foo')都会得到完全相同的返回对象,如果它将解析到相同的文件。
是否有一种方法使这个缓存无效?例如,对于单元测试,我希望每个测试都在一个新鲜的对象上工作。
当前回答
如果你总是想重新加载你的模块,你可以添加这个函数:
function requireUncached(module) {
delete require.cache[require.resolve(module)];
return require(module);
}
然后使用requireUncached('./myModule')而不是require。
其他回答
有一个简单模块(带测试)
我们在测试代码时遇到了这个问题(删除缓存模块,以便它们可以在新鲜状态下重新使用),所以我们审查了人们在各种StackOverflow问答上的所有建议,并将一个简单的node.js模块(带测试)放在一起:
https://www.npmjs.com/package/decache
如你所料,它既适用于已发布的npm包,也适用于本地定义的模块。Windows, Mac, Linux等等。
怎么做?(使用)
用法非常简单:
安装
从npm安装模块:
NPM安装decache——save-dev
在你的代码中使用它:
// require the decache module:
const decache = require('decache');
// require a module that you wrote"
let mymod = require('./mymodule.js');
// use your module the way you need to:
console.log(mymod.count()); // 0 (the initial state for our counter is zero)
console.log(mymod.incrementRunCount()); // 1
// delete the cached module:
decache('./mymodule.js');
//
mymod = require('./mymodule.js'); // fresh start
console.log(mymod.count()); // 0 (back to initial state ... zero)
如果你有任何问题或需要更多的例子,请创建一个GitHub问题: https://github.com/dwyl/decache/issues
我不能在回答的注释中整齐地添加代码。但我会使用@Ben Barkay的答案,然后将其添加到require中。uncache函数。
// see https://github.com/joyent/node/issues/8266
// use in it in @Ben Barkay's require.uncache function or along with it. whatever
Object.keys(module.constructor._pathCache).forEach(function(cacheKey) {
if ( cacheKey.indexOf(moduleName) > -1 ) {
delete module.constructor._pathCache[ cacheKey ];
}
});
假设您需要一个模块,然后卸载它,然后重新安装相同的模块,但使用了不同的版本,其包中有不同的主脚本。json,下一个require将失败,因为主脚本不存在,因为它缓存在Module._pathCache中
文件说:
当需要模块时,模块缓存在这个对象中。通过从该对象中删除键值,下一个require将重新加载该模块。这不适用于本机插件,因为重新加载将导致错误。
如果你想让一个模块永远不被缓存(有时对开发有用,但记得在完成时删除它!),你可以把delete require.cache[module.id];在模块内部。
解决方法是:
delete require.cache[require.resolve(<path of your script>)]
对于那些像我一样在这方面有点新手的人,这里有一些基本的解释:
假设你在根目录下有一个虚拟example.js文件:
exports.message = "hi";
exports.say = function () {
console.log(message);
}
然后像这样要求():
$ node
> require('./example.js')
{ message: 'hi', say: [Function] }
如果你在example.js中添加如下一行:
exports.message = "hi";
exports.say = function () {
console.log(message);
}
exports.farewell = "bye!"; // this line is added later on
并在控制台中继续,该模块没有更新:
> require('./example.js')
{ message: 'hi', say: [Function] }
这时你可以使用delete require.cache[require.resolve()]在luff的回答中指出:
> delete require.cache[require.resolve('./example.js')]
true
> require('./example.js')
{ message: 'hi', say: [Function], farewell: 'bye!' }
因此缓存被清理,require()再次捕获文件的内容,加载所有当前值。