首页 > 解决方案 > JSON 在 fs.writeFile() 之后吓坏了?

问题描述

我有这个database.json要写入的文件

最初它看起来像这样

{
    "users": [
        {
            "id": "470055904063127552",
            "credit": 10,
            "cooldowns": [
                
            ]
        },
        {
            "id": "533910695495073792",
            "credit": 15,
            "cooldowns": [
                
            ]
        }
    ]
}

但是,在写入之后,格式会突然变得异常,变成这样:

{
    "users": [
        {
            "id": "470055904063127552",
            "credit": 10,
            "cooldowns": []
        },
        {
            "id": "533910695495073792",
            "credit": 30,
            "cooldowns": []
        }
    ]
}                    "QUIZ": 1636251021979
                }
            ]
        }
    ]
}

这是我的代码:

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", () => {})
        })

奇怪的是console.log返回

{
    "users": [
        {
            "id": "470055904063127552",
            "credit": 10,
            "cooldowns": []
        },
        {
            "id": "533910695495073792",
            "credit": 30,
            "cooldowns": [
                {
                    "QUIZ": 1636251021979
                }
            ]
        }
    ]
}

这就是我想要的。

更奇怪的是,有时写入文件会起作用,而有时则不起作用。有任何想法吗?谢谢

PS 唯一搞砸的是 JSON 格式;没有返回其他错误,所有变量都已声明并正常工作

标签: javascriptnode.jsjsonfs

解决方案


基本上,我意识到我正在同时在多个进程中写入文件,所以一切都吓坏了。

解决方法是使用writeFileSync()JSON 文件,然后同步更新,防止两个进程同时运行。

或者,如果您需要同时写入文件,只需使用数据库即可。

该死的现在我觉得自己很愚蠢

编辑:正如布拉德指出的那样,您也可以在写入文件时锁定文件,以便写入不需要同步。无论哪种方式,都不要同时写入同一个文件。


推荐阅读