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

Node.js动态修改JSON文件后无法重新导入问题求助

问题根源

Node.js 的 require 机制会对加载的模块(包括 JSON 文件)进行缓存,第一次导入后,后续调用 require 都会直接返回缓存中的内容,不会重新读取磁盘上的文件,这就是你每次拿到的都是初始值的原因。

解决方案

方案1:手动清除缓存后重新导入

每次使用前,先从 require.cache 中删除对应 JSON 文件的缓存记录,再执行 require 就能拿到最新内容:

const path = require('path');
const app = require('express')();

app.use('/change', async (req, res) => {
    const jsonPath = path.join(__dirname, 'number.json');
    // 清除该文件的缓存
    delete require.cache[require.resolve(jsonPath)];
    // 重新导入
    const num = require(jsonPath).number;
    console.log(num);
    await modifyJsonFile(jsonPath, { number: num + 1 });
    res.end();
});

方案2:直接用文件系统读取解析(推荐)

绕开 require 缓存,使用 fs 模块直接读取文件内容并解析成 JSON,这样每次都会读取磁盘上的最新文件:

const path = require('path');
const fs = require('fs').promises;
const app = require('express')();

app.use('/change', async (req, res) => {
    const jsonPath = path.join(__dirname, 'number.json');
    // 读取文件内容
    const fileContent = await fs.readFile(jsonPath, 'utf8');
    // 解析为JSON对象
    const { number: num } = JSON.parse(fileContent);
    console.log(num);
    await modifyJsonFile(jsonPath, { number: num + 1 });
    res.end();
});
方案对比
  • 方案1:依赖 require 机制,需要手动管理缓存,适合偶尔修改文件的场景;
  • 方案2:完全脱离模块缓存,直接操作文件,逻辑更直观,适合需要频繁动态修改文件的场景。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.13 18:13:16