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

129
Visualizações
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 Respostas
Responde à pergunta

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 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