Skip to content
Advertisement

When writing to a json file, the writing isn’t fully overwriting the previous data

I am attempting to take some data from a JSON file, alter that data and overwrite the data of the original file with that new and altered data however when writing back to the file, some old data is being left behind.

My js code for reading, altering, and writing the files are as follows:

JavaScript

I am using electron with this HTML code:

JavaScript

This code is being called when I click on a div and it aims to remove that div from the screen and the JSON file. (e.target is the div I have clicked on)

After running this code and clicking on a div, my JSON file ends up looking like this:

JavaScript

EDIT: (a little more info) I have tested saving the new data to a different file which works fine and does not cause any issues. I have also read the file both in a text editor and inside the console and both give the same messy result.

EDIT 2: After further testing, I have discovered that there is something somewhere else in my js file that is interfering with the saving to the JSON file causing the resultant file to be a big mess. I have now added the full code to my file and am not exactly sure where the issues are and how to prevent them. Any pointers as to this would be much appreciated, thanks! Furthermore, I am using electron meaning I can use the Node.js fsPromises inside of my plain js code so when testing out my code please be mindful of that. Thanks!

Advertisement

Answer

After a lot of testing, I have discovered that when I am checking for a click on any of the LI elements, that is reading to the JSON at the same time as the delete function is writing to the JSON and this leads to a mess up in the JSON file.

In short, when reading and writing from and to a JSON file make sure that you are not doing both at the same time, to troubleshoot I added console.log statements after each read and write and saw that was sending overlapping requests that lead to the messy resultant JSON file.

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement