I have a function that writes data to a file when accessing the router!
Type of data 2023-12-08,0,12,44
Route
admin.get('/chart', async (req, res) => {
const posts = 12
const commnets = 44
const users = await db.getRepository(User)
.createQueryBuilder('user')
.where('user.created_at >= CURRENT_DATE')
.getCount()
const now = new Date()
const month = ('0' + (now.getMonth() + 1)).slice(-2)
const date = ('0' + now.getDate()).slice(-2)
const year = now.getFullYear()
const shortDate = year + '-' + month + '-' + date
fs.readFile(path.join("assets/data.csv"), 'utf8', (err: any, data: any) => {
if (err) throw err;
const newContent = shortDate + "," + users + "," + posts + "," + commnets;
const updatedData = `${data}${newContent}\n`;
fs.writeFile(path.join("assets/data.csv"), updatedData, { flag: 'w' }, (err: any) => {
if (err) throw err;
console.log('Content appended to file!');
});
});
res.status(200).json('Content appended to file!')
})
In this case, when accessing the router, the file will be overwritten and I get the same data from a new line.
Type of data 2023-12-08,0,12,44
I need to make it so that, when today's date is equal to the date of the last line, we overwrite it, or if a new day has come, then add a new line. And each time you access the route, overwrite only the line for the current date; do not delete the previous lines.
I would separate the write layer from the application logic. I would maintain a data structure on memory and flush that to the file system when I deem fit (maybe periodically).
Data
StatsManager
Finally in the request handler: