【问题标题】:Json file is formatted when you run the code运行代码时会格式化 Json 文件
【发布时间】:2020-09-14 00:12:47
【问题描述】:

我在 Discord 中有一个机器人,我正在实现一个 EXP 系统,信息保存在 JSON 中,但每次我因为 X 原因重新启动程序时,文件都会被格式化。

const db = require("./db.json");

if (!db[message.author.id]) {
            fs.readFile("./db.json", function(err,content) {
                if(err) throw err;
            }); 
            db[message.author.id] = {
                xp: 0,
                level: 1
            };
        }

【问题讨论】:

    标签: javascript node.js json discord.js


    【解决方案1】:

    在您的代码中,我认为问题在于您没有将修改后的 db 对象写入 json 文件......理想情况下,您的代码应该像......

    fs.readFile("./db.json", function(err,content) {
          if(err) throw err;
          db = JSON.parse(content); //we load updated db each time, require('db.json') only loads once...
          if (!db[message.author.id]) {
                db[message.author.id] = {
                    xp: 0,
                    level: 1
                };
               //You should have this after every update to db...
               fs.writeFileSync("./db.json",JSON.stringify(db));//this will now save file 
          }
    });
    

    文件被格式化的问题是因为每次更新 db JSON 时,它不会被写入文件,而只会在内存中更新,因此使用 fs.writeFileSync 应该将更新后的 db 写入文件,因此该文件将得到更新,而不是被格式化...

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-02-10
      • 2020-09-30
      • 1970-01-01
      • 2012-04-04
      • 2023-01-31
      • 1970-01-01
      • 1970-01-01
      • 2019-04-14
      相关资源
      最近更新 更多