gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 10:42:27 32 4
gpt4 key购买 nike

注意:这与 node.js require() cache - possible to invalidate? 不是同一个问题.

我正在编写一个脚本来修改 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是< em>仍在加载旧模块!

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

我的问题是:有什么方法可以让我访问和修改这个二级缓存吗?

最佳答案

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

关于node.js - 如何使缓存的 require.resolve() 结果无效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59865584/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com