I am making a game and am working on the accounts. When i have JSON stringify the object and save it to a file, it sometimes (occasionally and at random) writes:
{"example@domain.cm":{"email":"example@domain.cm","password":"myPassword","token":"c26a2a66-77f8-43d7-aa92-14da81979386"} >}< "example@domain.com":{"email":"example@domain.com","password":"myPassword","token":"209758d0-9a6e-4e99-835a-21595b822796"}}
when i am expecting:
{"example@domain.cm":{"email":"example@domain.cm","password":"myPassword","token":"c26a2a66-77f8-43d7-aa92-14da81979386"} >,< "example@domain.com":{"email":"example@domain.com","password":"myPassword","token":"209758d0-9a6e-4e99-835a-21595b822796"}}
My Code:
const fs = require('fs');
const { v4: newUuid } = require('uuid');
function save() {
fs.writeFile('save_info/users.json', JSON.stringify(User.USERS), err => {});
}
class User {
static USERS = {};
constructor(email, password, token = newUuid()) {
this.email = email;
this.password = password;
this.token = token;
User.USERS[email] = this;
save();
}
}
What is going on?
EDIT I am using nodemon. Whenever i save a file (except users.json), it automatically stops and starts it. I am also using express because this script is for the server part. (This is a private project, not looking to make it perfect, just learn)
Thank you, @jabaa
they have pointed out a warning that using fs.writeFile() multiple times without waiting for the callback is unsafe. Here is the solution:
var CAN_SAVE = true;
var PENDING_SAVE = false;
function save() {
if (!CAN_SAVE) {
PENDING_SAVE = true;
return;
}
PENDING_SAVE = false;
CAN_SAVE = false;
fs.writeFile('save_info/users.json', JSON.stringify(User.USERS), err => {
CAN_SAVE = true;
if (PENDING_SAVE) save();
});
}
Another solution is to use fs.writeFileSync(), which might actually be better in my case... (Thank you, @Steven Spungin)