简体   繁体   English

在 fs.writeFile() 之后 JSON 吓坏了?

[英]JSON freaking out after fs.writeFile()?

I have this database.json file that I want to write to我有要写入的database.json文件

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奇怪的是 console.log 返回

{
    "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谢谢

PS the only thing messed up is the JSON format; PS唯一搞砸的是JSON格式; no other errors are returned and all variables are declared and working没有返回其他错误,所有变量都已声明并正常工作

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.解决办法是使用writeFileSync() ,然后同步更新JSON文件,防止两个进程同时运行。

Or if you need to write to a file at the same time, just use a database.或者如果您需要同时写入文件,只需使用数据库。

damn now I feel stupid该死的,现在我觉得自己很愚蠢

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM