-1

I want to have persistent memory (store the user's progress) in a .json file in %AppData%. I tried doing this according to this post, but it doesn't work. For testing purposes I'm only working with storing one object.

The code below doesn't work at all. If I use fs.open(filePath, "w", function(err, data) { ... instead of readFile(..., it does create a json file in %AppData%, but then it doesn't write anything to it, it's always 0 bytes.

var nw = require('nw.gui');
var fs = require('fs');
var path = require('path');

var file = "userdata.json";

var filePath = path.join(nw.App.dataPath, file);

console.log(filePath); // <- This shows correct path in Application Data.

fs.readFile(filePath ,function (err, data) {
var idVar = "1";
var json = JSON.parse(data);
json.push("id :" + idVar);
fs.writeFile(filePath, JSON.stringify(json));
});

If anyone has any idea where I'm messing this up, I'd be grateful..

EDIT:

Solved, thanks to kailniris.

I was simply trying to parse an empty file

Community
  • 1
  • 1
angularchobo
  • 183
  • 1
  • 3
  • 17
  • Check out the background page console for errors. Node context errors will be logged there. Right click on the window then inspect background page. – kailniris Aug 17 '16 at 15:45
  • Uncaught SyntaxError: Unexpected end of JSON input – angularchobo Aug 17 '16 at 15:50
  • Which line? There is something wrong with your json or you want to parse an empty data as json. Console.log(data) before parse – kailniris Aug 17 '16 at 15:53
  • It was "var json = JSON.parse(data);". Yes, obviously it was empty. Thank you very much, now it works fine. On a side note, is there a way to work around this? There has to be a first entry, after all. – angularchobo Aug 17 '16 at 16:05
  • well yea, check if it's empty before you try to parse it... – Kevin B Aug 17 '16 at 16:13

1 Answers1

0

There is no json in the file you try to read. Before parsing data check if the file is empty. If it is then create an empty json, push the new data into it then write it to the file else parse the json in the file.

kailniris
  • 8,856
  • 2
  • 17
  • 24