I have an issue where I am writing data from an array to a JSON file every 10 secs on an express server, and this is causing the main page to reload whenever the writeFile function is called.
The main page makes a GET request to retrieve Entry objects in the array, however I don't understand why it is reloading when the array isn't being changed in anyway, it is just being used to write to the JSON file.
In index.js (server code):
const server = require('./app');
const { readFromFile, writeToFile } = require('./helpers/readWrite');
const port = process.env.PORT || 3000;
readFromFile();
// start the server
server.listen(port, () => {
console.log(`Listening at http://localhost:${port}`);
// set the server to save to file every 10 seconds
setInterval(writeToFile, 10000);
});
In readWrite.js:
const Entry = require('../models/entry'); // file containing array that the data is written from.
function writeToFile() {
const entriesDataStringified = JSON.stringify(Entry.all); // stringify the entriesData array
// write to the json file, overwriting any data already in the file
fs.writeFile('./data/entries.json', entriesDataStringified, (err) => {
// check for error when writing file
if (err) {
console.log(err);
} else {
console.log('File successfully written');
}
});
}
Retrieving entries on client side:
async function getPosts(e) {
try{
response = await fetch(`http://localhost:3000/search/page/${pageNum}`);
data = await response.json();
console.log(data)
data.entries.forEach(post => {
if(!postArray.includes(post)){
newestArray.push(post);
postArray.push(post);
emojiArray.push({id: post.id, emojis: {loveCount: false, laughCount: false, likeCount: false}})
};
});
console.log(emojiArray);
Post.drawAll();
pageNum++
} catch(err) {
console.log(err)
}
}
Thanks.