'discord.js v13 fs.readFile() causes a file to become unwritable

I have a discord bot that has a config file for all it's settings on different servers, I want to remove config per server if the bot is ever removed from said server so I have this:

const data = require('./data.json');
const fs = require('fs');

//This triggers on a client.on('guildDelete', async(guild) => {}); event
if (data[guild.id]) {
    fs.readFile('./dataFiles/data.json', function(err, json) {
        if (err) console.log(err);

        let serverData = JSON.parse(json);
        delete serverData[guild.id];

        fs.writeFile('./dataFiles/data.json', JSON.stringify(serverData), (err) => {
            if (err) console.log(err);
        });
    });
}

Now this does the job just fine, my problem is after this is executed...

//This triggers on a client.on('messageCreate', async(message) => {}); event
if (!data[message.guild.id]) {
    data[message.guild.id] = {
        swear: true,
        xp: false,
        timeout: false,
        novalogs: true,
        raid: false
    };
    fs.writeFile('./dataFiles/data.json', JSON.stringify(data), (err) => {
        if (err) console.log(err);
    });
}

This function here stops working completely and just doesn't write to the file when I add the bot back, I've searched and can't seem to find a solution, anyone got any ideas?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source