Search code examples
javascriptjsondiscord.jsrequire

Required JSON file has old values from before running the program


I am writing a discord bot using javascript (discord.js).

I use json files to store my data and of course always need the latest data.

I do the following steps:

  1. I start the bot
  2. I run a function that requires the config.json file every time a message is sent
  3. I increase the xp a user gets from the message he sent
  4. I update the users xp in the config.json
  5. I log the data

So now after logging the first time (aka sending the first message) I get the data that was in the json file before I started the bot (makes sense). But after sending the second message, I expect the xp value to be higher than before, because the data should have been updated, the file new loaded and the data logged again.

(Yes I do update the file every time. When I look in the file by myself, the data is always up to date)

So is there any reason the file is not updated after requiring it the second time? Does require not reload the file?

Here is my code:

function loadJson() {
    var jsonData = require("./config.json")
    //here I navigate through my json file and end up getting to the ... That won't be needed I guess :)
    return jsonData
}

//edits the xp of a user
function changeUserXP(receivedMessage) {
    let xpPerMessage = getJsonData(receivedMessage)["levelSystemInfo"].xpPerMessage
    jsonReader('./config.json', (err, data) => {
        if (err) {
            console.log('Error reading file:',err)
            return
        }
    //increase the users xp
    data.guilds[receivedMessage.guild.id].members[receivedMessage.author.id].xp += Number(xpPerMessage)
    data.guilds[receivedMessage.guild.id].members[receivedMessage.author.id].stats.messagesSent += 1
    fs.writeFile('./test_config.json', JSON.stringify(data, null, 4), (err) => {
        if (err) console.log('Error writing file:', err)
        })
    })
}

client.on("message", (receivedMessage) => {
    changeUserXP(receivedMessage)
    console.log(loadJson(receivedMessage))
});

I hope the code helps :)

If my question was not precise enough or if you have further questions, feel free to comment

Thank you for your help <3


Solution

  • This is because require() reads the file only once and caches it. In order to read the same file again, you should first delete its key (the key is the path to the file) from require.cache