JSON文件变量已更新,但index.js仍输出旧值,求不重启解决方法
实时读取更新的JSON文件内容解决方案
Node.js的require()函数会缓存加载的模块(包括JSON文件),第一次加载后,后续调用只会返回缓存内容,不会重新读取磁盘上的最新文件,这就是你重启前一直拿到旧值的原因。以下是几种可行的解决方法:
方法1:同步读取并解析JSON(简单直接)
替换require为fs.readFileSync手动读取文件,确保每次都获取最新内容:
const fs = require('fs'); const path = require('path'); interval = setInterval(function() { // 用绝对路径避免相对路径问题 const filePath = path.resolve(__dirname, './../../server/oxide/data/online.json'); // 读取文件并解析为JSON对象 const rawContent = fs.readFileSync(filePath, 'utf8'); const online = JSON.parse(rawContent); // 原状态更新逻辑保持不变 if (online.ONLINE === -1) { client.user.setStatus('dnd'); client.user.setActivity('server offline'); } else if (online.ONLINE === 0) { client.user.setStatus('idle'); client.user.setActivity('no one'); } else { client.user.setStatus('online'); client.user.setActivity(`Players ${online.ONLINE}/500`); } console.log(`update ${online.ONLINE}`); }, 10000);
方法2:异步读取(非阻塞,更优性能)
如果担心同步读取阻塞事件循环,使用fs.readFile异步版本:
const fs = require('fs'); const path = require('path'); interval = setInterval(function() { const filePath = path.resolve(__dirname, './../../server/oxide/data/online.json'); fs.readFile(filePath, 'utf8', (err, rawContent) => { if (err) { console.error('读取online.json失败:', err); return; } try { const online = JSON.parse(rawContent); // 状态更新逻辑 if (online.ONLINE === -1) { client.user.setStatus('dnd'); client.user.setActivity('server offline'); } else if (online.ONLINE === 0) { client.user.setStatus('idle'); client.user.setActivity('no one'); } else { client.user.setStatus('online'); client.user.setActivity(`Players ${online.ONLINE}/500`); } console.log(`update ${online.ONLINE}`); } catch (parseErr) { console.error('解析JSON失败:', parseErr); } }); }, 10000);
方法3:清理require缓存(不推荐,仅作备选)
如果一定要保留require用法,可以每次加载前删除对应文件的缓存,但这种方法可能影响其他模块对该文件的引用,需谨慎使用:
const path = require('path'); interval = setInterval(function() { const filePath = path.resolve(__dirname, './../../server/oxide/data/online.json'); // 删除缓存 delete require.cache[filePath]; // 重新加载文件 const online = require(filePath); // 状态更新逻辑不变 if (online.ONLINE === -1) { client.user.setStatus('dnd'); client.user.setActivity('server offline'); } else if (online.ONLINE === 0) { client.user.setStatus('idle'); client.user.setActivity('no one'); } else { client.user.setStatus('online'); client.user.setActivity(`Players ${online.ONLINE}/500`); } console.log(`update ${online.ONLINE}`); }, 10000);
内容的提问来源于stack exchange,提问作者ART0022VI
相关产品推荐
相关产品推荐

