Javascript Json文件是在运行代码时格式化的

Javascript Json文件是在运行代码时格式化的,javascript,node.js,json,discord.js,Javascript,Node.js,Json,Discord.js,我在Discord中有一个bot,我正在实现一个EXP系统,信息保存在一个JSON中,但是每次由于X原因重新启动程序时,文件都会格式化 const db = require("./db.json"); if (!db[message.author.id]) { fs.readFile("./db.json", function(err,content) { if(err) throw err; });

我在Discord中有一个bot,我正在实现一个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
            };
        }

在您的代码中,我相信问题在于您没有将修改后的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写入文件,因此文件应该得到更新而不是格式化