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

Node.js+Express后端未重启无法更新JSON文件的解决方法

解决Node.js Express返回JSON文件不更新的问题

问题根源在于Node.js的require()函数会缓存已加载的模块(包括JSON文件),第一次加载后,后续调用require(path)都会直接返回缓存内容,不会重新读取修改后的文件。以下是几种可行的解决方案:

方案1:改用fs读取并手动解析JSON

直接绕过require缓存,每次请求都读取最新文件内容:

const express = require('express');
const fs = require('fs');

const app = express();
app.use(express.json());

const myDataPath = "/var/data/";

app.get("/:id", (request, response) => {
    let id = request.params.id;
    let path = myDataPath + id + ".json";

    if (fs.existsSync(path)) {
        fs.readFile(path, 'utf8', (err, data) => {
            if (err) return response.sendStatus(500);
            try {
                const jsonData = JSON.parse(data);
                response.json(jsonData);
            } catch (parseErr) {
                response.sendStatus(500);
            }
        });
    } else {
        response.sendStatus(404);
    }
});

方案2:每次请求前清除对应文件的require缓存

如果仍想使用require,可以在加载前删除缓存项:

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

const app = express();
app.use(express.json());

const myDataPath = "/var/data/";

app.get("/:id", (request, response) => {
    let id = request.params.id;
    let filePath = myDataPath + id + ".json";
    const resolvedPath = path.resolve(filePath);

    if (fs.existsSync(filePath)) {
        // 清除该文件的缓存
        delete require.cache[resolvedPath];
        response.json(require(resolvedPath));
    } else {
        response.sendStatus(404);
    }
});

方案3:监听文件变化自动清除缓存

适合频繁修改文件的场景,通过监听目录自动处理缓存:

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

const app = express();
app.use(express.json());

const myDataPath = "/var/data/";

// 监听数据目录的文件修改事件
fs.watch(myDataPath, (eventType, filename) => {
    if (filename && eventType === 'change') {
        const resolvedPath = path.resolve(myDataPath, filename);
        delete require.cache[resolvedPath];
    }
});

app.get("/:id", (request, response) => {
    let id = request.params.id;
    let filePath = myDataPath + id + ".json";
    const resolvedPath = path.resolve(filePath);

    if (fs.existsSync(filePath)) {
        response.json(require(resolvedPath));
    } else {
        response.sendStatus(404);
    }
});

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 02:45:31