Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

104
Views
JSON is not properly turning an object into a string

I am making a game and am working on the accounts. When i have JSON stringify the object and save it to a file, it sometimes (occasionally and at random) writes:

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

when i am expecting:

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

My Code:

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();
    }
}

What is going on?

EDIT I am using nodemon. Whenever i save a file (except users.json), it automatically stops and starts it. I am also using express because this script is for the server part. (This is a private project, not looking to make it perfect, just learn)

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

Thank you, @jabaa they have pointed out a warning that using fs.writeFile() multiple times without waiting for the callback is unsafe. Here is the solution:

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();
    });
}

Another solution is to use fs.writeFileSync(), which might actually be better in my case... (Thank you, @Steven Spungin)

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!