【问题标题】:JSON is not properly turning an object into a stringJSON 没有正确地将对象转换为字符串
【发布时间】: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 问题,而是文件访问/写入问题。
  • 您预期的版本中存在无效的&gt;&lt;
  • 什么是User.USERS?请提供minimal reproducible example
  • 会不会是这个问题:“在同一个文件上多次使用fs.writeFile()而不等待回调是不安全的。”

标签: javascript json tostring


【解决方案1】:

谢谢你,@jabaa 他们指出了一个警告,即多次使用fs.writeFile() 而不等待回调是不安全的。这是解决方案:

var CAN_SAVE = true;
var PENDING_SAVE = false;
function save() {
    if (!CAN_SAVE) {
        PENDING_SAVE = true;
        return;
    }
    PENDING_SAVE = false;
    CAN_SAVE = false;
    fs.writeFile('save_info/users.json', JSON.stringify(User.USERS), err => {
        CAN_SAVE = true;
        if (PENDING_SAVE) save();
    });
}

另一种解决方案是使用fs.writeFileSync(),在我的情况下这实际上可能更好......(谢谢@Steven Spungin)

【讨论】:

  • 或者只使用同步写入。
  • @StevenSpungin 是的,我想这也行XD
  • 不要在服务器请求处理程序中使用writeFileSync
猜你喜欢
  • 2021-08-03
  • 1970-01-01
  • 2014-03-23
  • 1970-01-01
  • 2010-09-07
相关资源
最近更新 更多