I have this database.json file that I want to write to
and originally it will look like this
{
"users": [
{
"id": "470055904063127552",
"credit": 10,
"cooldowns": [
]
},
{
"id": "533910695495073792",
"credit": 15,
"cooldowns": [
]
}
]
}
However, after writing to it, the format will suddenly freak out and turn into something like this:
{
"users": [
{
"id": "470055904063127552",
"credit": 10,
"cooldowns": []
},
{
"id": "533910695495073792",
"credit": 30,
"cooldowns": []
}
]
} "QUIZ": 1636251021979
}
]
}
]
}
Here is my code:
fs.readFile(database_name, "utf-8", (err, data) => {
if(err) return console.log(err);
obj = JSON.parse(data);
const cooldowns = obj.users[obj.users.findIndex(v => v.id === user)].cooldowns;
if(!cooldowns.QUIZ)
{
cooldowns.push({ "QUIZ": new Date().getTime() + 86400000 })
}
json = JSON.stringify(obj, null, 4);
console.log(json);
fs.writeFile(database_name, json, "utf-8", () => {})
})
The peculiar thing is console.log returns
{
"users": [
{
"id": "470055904063127552",
"credit": 10,
"cooldowns": []
},
{
"id": "533910695495073792",
"credit": 30,
"cooldowns": [
{
"QUIZ": 1636251021979
}
]
}
]
}
which is what I want.
And an even stranger thing is that sometimes writing to the file will work, and other times, it doesn't. Any ideas? Thanks
P.S. the only thing messed up is the JSON format; no other errors are returned and all variables are declared and working
Basically what I realised is that I'm writing to the file in more than one process at the same time, so everything just freaks out.
The solution is to use writeFileSync() and then update the JSON file synchronously, preventing two processes from running at once.
Or if you need to write to a file at the same time, just use a database.
damn now I feel stupid
Edit: As Brad pointed out, you can also lock the file when writing to it so that writing need not be synchronous. Either way, just don't write to the same file at the same time.