0

I have a backend where every time it gets called, it imports a local JSON file and prints its content, what it also does at the end is dynamically modifying the JSON file at runtime. However, an issue I seem to encounter is that every time it prints the content, it is always the content at the first time the module was imported, instead of the content after the many times it was dynamically modified. To better illustrate, my JSON looks like the following

{
    "number": 1
}

My backend looks like

app.use('/change', async (req, res) => {
    const num = require('number.json').number;
    console.log(num);
    await modifyJsonFile(
        path.join(__dirname, 'number.json'),
        {
            number: num + 1
        }
    );
    res.end();

}

Now the interesting thing happens. When I call it the first time, it would print "1", and the number in the JSON file changes to "2". When I call it the second time, it would still print "1", even though the property in the JSON file is "2". My guess for the issue is that the backend has always been using the JSON module the first time it was imported. Any possible solutions? especially on re-importing the modified module, or alternative walk-around? Thanks.

  • 1
    Use the fs module and read/parse the file. `require` is not the right method for that. Although its possible with deleting the cache: https://stackoverflow.com/a/16060619/5781499 – Marc Aug 08 '23 at 15:28

1 Answers1

1

It looks like it is happening due to cache. It gets updated correctly but every time you try to access it , it accesses the cache rather that the updated one . So, the solution will be something like adding cache removal code after each import , so that the next time you access it , it gets the latest one for you. The sample will be like this

app.use('/change', async (req, res) => {
const filePath = path.join(__dirname, 'number.json');// You can give path accordingly 

delete require.cache[filePath]; // Clears the  cache here 

const num = require(filePath).number;
console.log(num);
//Rest of code 

Here in filePath , we have to provide dirname as caching works differently wrt to where we call it , so we provide the path there.

Refer- Node Documentation here

This is supposed to work .