javascript - 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 格式;没有返回其他错误,所有变量都已声明并正常工作
解决方案
基本上,我意识到我正在同时在多个进程中写入文件,所以一切都吓坏了。
解决方法是使用writeFileSync()
JSON 文件,然后同步更新,防止两个进程同时运行。
或者,如果您需要同时写入文件,只需使用数据库即可。
该死的现在我觉得自己很愚蠢
编辑:正如布拉德指出的那样,您也可以在写入文件时锁定文件,以便写入不需要同步。无论哪种方式,都不要同时写入同一个文件。
推荐阅读
- lua - GMod - lua 代码似乎不起作用,但没有显示错误
- mysql - Mysqldump 强制 BEGIN 和 END 触发
- windows - 徽章在 Windows 10 上的固定网站中不起作用
- python - Python 的 hash() 函数返回的最大值/最小值
- plotly-dash - 如何将 Choroplethmapbox 无花果添加到图形中?
- sql - 如何相互比较行并根据条件仅保留一行
- computer-vision - 关于通过appsrc将cv::Mat保存到mp4文件的问题
- c++ - 如何解决预编译头错误
- flutter - Flutter Firestore:如何做类似于 where('fieldName', arrayNotContains: 'something') 的事情?
- r - kable 表未正确显示在 github 上