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

JavaScript(Discord.js)中如何在while循环内同步读取文件

问题原因
  • 第一个错误是你误用了fs.readFileSyncAPI:同步读取接口不接收回调函数作为参数,你传入的回调逻辑完全不会执行,这就导致修改run变量的代码永远不会触发,run始终为true,程序直接进入死循环卡死。
  • 哪怕你换成异步的fs.readFile,逻辑也跑不通:JavaScript是单线程事件循环模型,同步执行的while循环会一直占用主线程,所有异步回调都要等同步任务全部清空才会执行,也就是说只要while循环不结束,你写的文件读取回调永远不会被调度,run还是永远变不成false,依然是死循环。
修复方案

你要使用同步读取的话,直接把jsonReader改成纯同步实现,不要用回调逻辑,直接返回解析结果即可,参考修改后的完整代码:

module.exports = {
    name: 'xprun',
    description: "runs the xp handler",
    execute(message) {
        const name = message.author.username;
        const server = message.guild.id;
        const fs = require('fs');

        // 同步json读取函数,读取成功返回解析后的对象,出错直接抛出异常
        function jsonReaderSync(filePath) {
            const fileData = fs.readFileSync(filePath, 'utf-8');
            return JSON.parse(fileData);
        }

        console.log('Starting the loop...');
        
        // 要跑5次直接用for循环更简洁,不需要额外维护run变量
        for (let i = 0; i < 5; i++) {
            console.log('Running the loop...');
            try {
                // 读取第一个文件
                const rankData = jsonReaderSync(`./userData/rank/${server}_server/1.json`);
                console.log(rankData.id);
                // 读取第二个文件
                const xpData = jsonReaderSync(`./userData/xp/${server}_server/${name}_xp.json`);
                console.log(xpData.rank);
                console.log('The loop was completed');
            } catch (err) {
                console.log(err);
            }
        }

        console.log('The loop was ended');
    }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 01:15:05