【发布时间】:2022-01-06 18:31:53
【问题描述】:
我正在制作游戏并处理帐户。当我让 JSON 对对象进行字符串化并将其保存到文件时,它有时(偶尔和随机)会写道:
{"example@domain.cm":{"email":"example@domain.cm","password":"myPassword","token":"c26a2a66-77f8-43d7-aa92-14da81979386"} >}< "example@domain.com":{"email":"example@domain.com","password":"myPassword","token":"209758d0-9a6e-4e99-835a-21595b822796"}}
当我期待时:
{"example@domain.cm":{"email":"example@domain.cm","password":"myPassword","token":"c26a2a66-77f8-43d7-aa92-14da81979386"} >,< "example@domain.com":{"email":"example@domain.com","password":"myPassword","token":"209758d0-9a6e-4e99-835a-21595b822796"}}
我的代码:
const fs = require('fs');
const { v4: newUuid } = require('uuid');
function save() {
fs.writeFile('save_info/users.json', JSON.stringify(User.USERS), err => {});
}
class User {
static USERS = {};
constructor(email, password, token = newUuid()) {
this.email = email;
this.password = password;
this.token = token;
User.USERS[email] = this;
save();
}
}
发生了什么事?
编辑 我正在使用节点蒙。每当我保存文件(users.json 除外)时,它都会自动停止并启动它。我也在使用 express,因为这个脚本是用于服务器部分的。 (这是一个私人项目,不求完美,只是学习)
【问题讨论】:
-
你能提供你用来做这个的代码吗,没有它很难给出准确的答案
-
这看起来不像是 JSON.stingify 问题,而是文件访问/写入问题。
-
您预期的版本中存在无效的
>和< -
什么是
User.USERS?请提供minimal reproducible example。 -
会不会是这个问题:“在同一个文件上多次使用
fs.writeFile()而不等待回调是不安全的。”
标签: javascript json tostring