0

I have a little problem with node js.

If I save a file with fs.writeFile it saves but the file has no content, but if I read the file and print the content there is content in the file

Thats the node js code to save the file:

let sjson = JSON.parse(fs.readFileSync("./saves/User_VipList.json", "utf8"));
    sjson['users'].push({"name": args[0]});
    fs.writeFile("./saves/User_VipList.json", JSON.stringify(sjson), (err) => {
      if(err) throw err;
      
    });

Thats how i read the content:

let sjson = JSON.parse(fs.readFileSync("./saves/User_VipList.json", "utf8"));
    console.log(sjson);
    

And that's the JSON file:

{
    "users": []
}

But in users should be content because

Hope you guys can help me

Saheb
  • 1,392
  • 3
  • 13
  • 33

2 Answers2

0

Due to async nature looks like your program doesnt wait when file write ends occurs, so please try to use fs.writeFileSync instead, for example:

try {
  fs.writeFileSync("./saves/User_VipList.json", JSON.stringify(sjson))
} catch(err) {
  console.log('Error writing file:', err)
}
Denisix
  • 106
  • 1
  • Seems like this didn't fix it file is still empty. but there is still output with content. – Tobias Staffel Jul 20 '20 at 09:05
  • try to check what content in `sjson`, and after stringify by inserting `console.log(sjson)` and `console.log(JSON.stringify(sjson))` before fs.writeFileSync – Denisix Jul 20 '20 at 09:58
-1

Found the Problem

Oh i think i found the problem if i start node index.js with a bat file the problem happends but if i start node manually over cmd it works.

Didn't mention the Bat file because i didn't think thats could be a problem :)

But why is that a problem?