Javascript 如何在更改JSON文件后将其重新加载为模块

Javascript 如何在更改JSON文件后将其重新加载为模块,javascript,node.js,Javascript,Node.js,我有一个配置JSON模块config.JSON如下: { "comment": "This is old config" } 我使用require('./config.json')将其作为模块导入。在我的源代码中,我希望更新JSON文件的内容,并像重新加载新内容一样重新加载: { "comment": "This is new config" } 例如,在index.js中,我将重写config.json文件并重新导入,如下所示: const fs=require(“fs”)

我有一个配置JSON模块
config.JSON
如下:

{
    "comment": "This is old config"
}
我使用
require('./config.json')
将其作为模块导入。在我的源代码中,我希望更新JSON文件的内容,并像重新加载新内容一样重新加载:

{
    "comment": "This is new config"
}
例如,在
index.js
中,我将重写
config.json
文件并重新导入,如下所示:

const fs=require(“fs”);
常量路径=要求(“路径”);
让config=require(“./config.json”);
log('Old:'+config.comment);
//重写配置
让newConfig={
注释:“这是新配置”
};
fs.writeFileSync(
join(process.cwd(),“config.json”),
stringify(newConfig,null,“\t”)
);
//在这里重新加载配置
config=require(“./config.json”);
log('New:'+config.comment);
控制台的输出:

Old: This is old config
New: This is old config
我看到JSON内容更新了,但我无法重新加载模块,
config
变量仍然包含以前相同的缓存数据。如何将JSON文件重写和重新导入为模块

如有任何建议,我们将不胜感激

const fs = require("fs");
const path = require("path");
let config = require("./config.json");

console.log('Old: ' + config.comment);

// Rewrite config
let newConfig = {
  comment: "This is new config"
};

fs.writeFileSync(
  path.join(process.cwd(), "config.json"),
  JSON.stringify(newConfig, null, "\t")
);

// Reload config here
delete require.cache[require.resolve('./config.json')]   // Deleting loaded module
config = require("./config.json");
console.log('New: ' + config.comment);

在重新加载之前,只添加了一行代码来删除预加载的模块。

可能与@ambianBeing重复,但您的引用没有提供答案?在更新
config.json
之后,尝试使用
require('./config.json')
以便您使用json文件作为数据,并且当该文件更改时,您希望重新读取该数据?或者重建时,是否要重新加载模块<代码>要求(ing)如果它是数据,那么这样做是错误的。用于加载源代码的,除非重新运行源代码,否则不会更改。@ThanhPhan因为节点中的AIK模块解析是通过依赖路径(相对/绝对)和引擎盖下的
require
uses
require.resolve()
其中生成的
缓存
字典包含
作为
路径
。这就是为什么我们必须通过路径解析和删除。如果那个断言是错误的,请(任何人)纠正我。