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
相关产品推荐
相关产品推荐

