You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Node.js中修改JSON配置模块后如何重新加载该模块?

如何重新加载已修改的JSON配置模块

你遇到的问题是Node.js的模块缓存机制导致的——Node.js为了提升性能,会把已经通过require()加载过的模块(包括JSON文件)缓存到require.cache对象里,后续再调用require()时会直接返回缓存的内容,不会重新读取磁盘上的文件,哪怕文件已经被修改了。

下面给你两种可行的解决方案:

方案1:清除模块缓存后重新require

在重新加载配置前,先从require.cache中删除对应模块的缓存项,这样再次调用require()时就会重新读取最新的文件内容。

修改你的示例代码如下:

const fs = require("fs");
const path = require("path");
let config = require("./config.json");
console.log('Old: ' + config.comment);

// 重写配置
let newConfig = { comment: "This is new config" };
fs.writeFileSync(
  path.join(process.cwd(), "config.json"),
  JSON.stringify(newConfig, null, "\t")
);

// 清除对应模块的缓存
const configPath = path.resolve(__dirname, "./config.json");
delete require.cache[configPath];

// 重新加载配置
config = require("./config.json");
console.log('New: ' + config.comment);

这里用path.resolve(__dirname, "./config.json")获取模块的绝对路径(因为require.cache的键是模块的绝对路径),然后删除缓存项,之后再require就能拿到最新内容了。

方案2:直接读取文件并解析(绕过模块缓存)

如果你的配置需要频繁更新,更推荐直接使用fs模块读取文件,然后手动解析JSON,这样完全绕过Node.js的模块缓存,每次都读取最新的文件内容:

修改后的示例代码:

const fs = require("fs");
const path = require("path");

// 封装一个读取配置的函数
function loadConfig() {
  const configPath = path.join(process.cwd(), "config.json");
  const configContent = fs.readFileSync(configPath, "utf8");
  return JSON.parse(configContent);
}

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

// 重写配置
let newConfig = { comment: "This is new config" };
fs.writeFileSync(
  path.join(process.cwd(), "config.json"),
  JSON.stringify(newConfig, null, "\t")
);

// 重新加载配置
config = loadConfig();
console.log('New: ' + config.comment);

这种方式更灵活,尤其适合需要动态更新配置的场景,不需要关心模块缓存的问题。

执行修改后的代码,控制台就会正确输出:

Old: This is old config
New: This is new config

内容的提问来源于stack exchange,提问作者TLePhan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.14 06:59:47