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

137
Vistas
JSON freaking out after fs.writeFile()?

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

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

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.

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