Home > other >  Nodejs reads an outdated version of a JSON file
Nodejs reads an outdated version of a JSON file

Time:02-01

I am writing a website to run in node js.

I have a webpage that reads a JSON file that contains data in the form:

# names.json:
["name1", "name2", "name3"]

Then within my server side code, I have a get request that reads data from names.json and sends it my webpage.

Within my code all lies a post request that may change the contents of names.json by using a form on another page.

# names.json becomes:
["name4", "name5", "name6"]

The post request is able to change data in names.json correctly. This because I will often check the json file manually to check the changes I have made are applied.

But when I try to use the get request (which is triggered using a button within a form with a method of "get") it would appear the get request is using a version of the names.json where the changes had not applied at all. This is really confusing me.

My code goes like this:

app.get('/getRequest', function(req, resp){
    let isLoggedIn = req.session.loggedin;
    let currentUser = req.session.username;
    if (isLoggedIn == true && (currentUser != null || currentUser != '')) {
        let joinTable = require("./names.json","utf-8");
        for (let i = 0; i < Object.keys(joinTable).length; i  ) {
            // Syntax to analyse data from names.json...
            // Here the get request should see name4, name5 and name6
            // Instead it sees name1, name2 and name3 from before
        }
        // Syntax to send the data from names.json to profile.html.
        resp.redirect('/profile.html')
    } else {
        makeAlert("You are currently not logged in.");
        resp.redirect('/');
    }
    resp.end();

As mentioned earlier. This GET request will use the data in names.json seen BEFORE any changes from the POST request is made. That is, it will be as if the POST request never occurred in the first place.

I am able to recognise this because I may get name1, name2 and name3, instead of name4, name5andname6``` - the changes made in the post request.

Does anyone know why this happening?

Any insight or help would be greatly appreciated!

CodePudding user response:

require caches file content. You have to read it from the file system each time(https://stackoverflow.com/a/25710749/1333262), or clear the cache of require (node.js require() cache - possible to invalidate?)

  •  Tags:  
  • Related