Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

110
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda