如何使缓存的require.resolve()结果无效



注意:这与node.js require((缓存不是同一个问题 - 可能失效?

我正在编写一个脚本,用于修改 Node.js 包package.json中的main入口点,并且很难测试其行为。

下面是我尝试修改其main入口点的示例包。它由三个文件组成。

./node_modules/example/package.json

{
"name": "example",
"version": "1.0.0",
"main": "a.js"
}

./node_modules/example/a.js

module.exports = { letter: 'A' }

./node_modules/example/b.js

module.exports = { letter: 'B' }

如您所见,此包现在加载a.js,但我的脚本会将其更改为加载b.js

这是我的脚本:

const fs = require('fs')
// Here is what we get at first
const first = require('example')
console.log(first) // { letter: 'A' }
// Now rewrite the package.json
const p = JSON.parse(fs.readFileSync('./node_modules/example/package.json', 'utf8'))
console.log(p.main) // 'a.js'
p.main = 'b.js'
fs.writeFileSync('./node_modules/example/package.json', JSON.stringify(p, null, 2))
// Require the module a second time
// We get the same object a second time, because of well-documented caching behaviour
// <https://nodejs.org/api/modules.html#modules_caching>
const second = require('example')
console.log(second === first) // true
console.log(second) // { letter: 'A' }
// Clear the cache, as documented
// <https://nodejs.org/api/modules.html#modules_require_cache>
// <https://stackoverflow.com/questions/9210542/node-js-require-cache-possible-to-invalidate/16060619>
delete require.cache[require.resolve('example')]
// Require the module a third time
// We get a new object... but it's still the old entry point
const third = require('example')
console.log(third === first) // false - a new object
console.log(third) // { letter: 'A' } - STILL THE SAME? should be 'B'

如您所见,在重写并保存新package.json并清除require缓存后,Node.js仍在加载旧模块!

深入挖掘,我发现从require.resolve('example')返回的值仍然是./node_modules/example/a.js,即使它现在应该./node_modules/example/b.js。换句话说,看起来好像有某种辅助缓存 对于require.resolve的结果。

我的问题是:有什么方法可以访问和修改此辅助缓存吗?

目前无法做到这一点。Node.js加载的每个package.json的内容都单独缓存在一个变量packageJsonCache中,如果不向Node.js模块API添加新功能,外部无法访问该变量。

最新更新