require.cache
当模块被加载时,它们会缓存到这个对象中。通过从该对象中删除一个键值,下次 require 时将会重新加载该模块。这不适用于 本地插件,重新加载 本地插件 会导致错误。
【Modules are cached in this object when they are required. By deleting a key
value from this object, the next require will reload the module.
This does not apply to native addons, for which reloading will result in an
error.】
添加或替换条目也是可能的。在检查内置模块之前会先检查此缓存,如果将与内置模块同名的条目添加到缓存中,只有带有 node: 前缀的 require 调用才能接收到内置模块。请谨慎使用!
【Adding or replacing entries is also possible. This cache is checked before
built-in modules and if a name matching a built-in module is added to the cache,
only node:-prefixed require calls are going to receive the built-in module.
Use with care!】
const assert = require('node:assert');
const realFs = require('node:fs');
const fakeFs = {};
require.cache.fs = { exports: fakeFs };
assert.strictEqual(require('node:fs'), fakeFs);
assert.strictEqual(require('node:fs'), realFs);