I’m using javascript because I have no choice : the api that i’m using is in javascript and only in javascript. I’ve no knowledge about it at all. I’m trying to do a quit function that store data (polls list) in case in of an error before exiting. In parallel of that I have an init function that restore the data.
function quit() {
fs.readFile(pollsName, "utf8", function readFileCallback(err, data) {
// never reach this line
if (err) {
console.log(err);
} else {
obj = JSON.parse(data); //now it an object
obj.poll = polls.map((poll) => poll.serialize);
json = JSON.stringify(obj); //convert it back to json
fs.writeFile(jsonName, json, (e) => {
if (e) throw e;
console.log("Polls saved");
}); // write it back
}
});
exit(1);
}
As you can see I never enter in the readFile() function. However I have another function write() that correctly store logs in similar file. The file name is correct, it is a json file with a key "poll" that represent an empty list. Both fs and exit package are import with "require".
I currently have no clue to solve this situation and i’m struggling on it. At first I was handling signal but I realised it wasn’t possible because write/read are unsafe. With this solution I’m going to catch every error and start this function.
Thank you if you can help me to find a solution
>Solution :
You call readFile
, but then you immediately terminate the porgram using exit(1)
. Simply move the exit(1)
into the callback function readFileCallback
, so your program terminates after the polls are saved.