Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

106
Visualizações
JSON is not properly turning an object into a string

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)

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

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)

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda