user13374843
user13374843

Reputation:

Json file is formatted when you run the code

I have a bot in Discord, I am implementing an EXP system, the information is saved in a JSON, but every time I restart the program for X reason the file is formatted.

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
            };
        }

Upvotes: 1

Views: 34

Answers (1)

Sankalp Bhamare
Sankalp Bhamare

Reputation: 553

In your code I believe the problem is that you are not writing the modified db object to the json file... ideally your code should be like...

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 
      }
});

The problem that the file gets formatted is because everytime you update your db JSON , it does not get written to the file , rather only updated in the memory, hence using fs.writeFileSync should write the updated db to the file and hence the file shall get updated and not get formatted...

Upvotes: 1

Related Questions