I have this endpoint that will write a static file with json data in to it.
fs.writeFile("name.json", JSON.stringify(JSON.parse(data)), function (err) {
if (err) {
return console.log(err);
}
console.log("The file was saved!");
});
And then i have another endpoint that will send the data inside this json file.
const fileData = require("./name.json")
res.json(fileData)
However after i trigger a change inside the file and then try to get that new data its not getting the new data instead sends the old one. But if i refresh the server and then try to get it it will send me the new data. I can see inside the file that changes are there after i write data but it still doesn't send the new data. It feels like some kind of caching. Ive tried to disable etag but still no success.
app.set('etag', false)
app.use(express.static("*", {
etag: false,
}))
CodePudding user response:
When you start the server, filedata
is read once and it is then available in memory, regardless of file changes, which is why you can get fresh data only after restarting the server.
It's caching, but it's not traffic caching, see: What is require?
What you actually need is to read the file every time you access it.
So, instead of require
, you could just read the file every time you access it, and get fresh data (and since it's JSON, you'd need to parse it before sending it):
const fileData = fs.readFileSync("./npm");
res.json(JSON.parse(fileData));