Reading message from JSON file sometimes outputs an old message


#1

Hello, I am having this problem now but in code. I am saving informations from server.js to a json file
(I am using remiexed project)


Then in view/app.js after window load event i am trying to load the json file and get values. But after first and few more refreshes i get old value. After i refresh project using console and refresh page i get new values.


Json files does not visualy update (Feedback / Question)
#2

Hey @TGamingStudio when you say you get an old message, how old do you mean? How does the message being sent from app.js compare to the list of recent messages in the log?

There are two things that could be at play here after a quick perusal of your code:

  1. You’re requireing the content of main.json outside of the request to /resolution-data, so you might be getting stale content there (i.e. the contents of main.json may have changed between when it was parsed and when it’s requested).
  2. you’re using fs.writeFile(), which is an asynchronous operation, so you might be returning from the client message handler before the write is done. If you’re somehow using the return of the client message handler as a cue to read the message from the file, you may be getting the message before fs.writeFile() is complete. You could switch to fs.writeFileSync() if you want to eliminate that as a possible problem.

I suspect that the “corrected” values after refresh are probably a result of the timing, not of the actual execution of the refresh command. I’m going to split this out into a new topic, because I don’t think it’s related.


#3

Yes :grin:
I made change in this part of code. It will refresh the json and send. Thanks!

app.get('/resolution-data', function(request, response) {
 
 const json = JSON.parse(fs.readFileSync("./main.json"))
 
 response.send(json);
});

MOD EDIT: formatting


#4

Ok, I think there are a couple more things going on here:

  1. you still have the require statement for loading main.json outside of the code that handles /resolution-data. Therefore that file is only required once when the project starts, and if it changes between then and when the data is requested you won’t get the new info.
  2. even if you move it into the GET handler you’ll still get stale data due to Node’s require cache. You’d need to clear the cache key for the file you’re pulling in every time you run the GET code and re-require the file. Personally I’d probably read the file in using fs instead of trying to require it.

When you run refresh in the console that restarts your project, so it triggers a refresh of the required file data. That’s why you’re getting the new content after you run that command.


#5

Oh i accidentaly edited last message. I wanted to reply Again. But it works! Thanks