How can I overwrite a line in a file via node:fs?

67 Views Asked by At

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.

1

There are 1 best solutions below

0
On

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

{ dateTime: number, users: number, posts: number, comments: number }

StatsManager

class StatsManager {

  constructor() {
     this.stats = this.loadStatsFromFileSystem();
  }

   parseStatsFileContents(contents) {
      // Parse the contents into array of data structure similar to the one provided above & return the same
   }

  loadStatsFromFileSystem() {
    // Load the file using fs module
    return this.parseStatsFileContents(fileContent);
  }

  async serializeStats() {
    // Write code to serialize the stats array into the current format of the file & return the same
  }

  syncWithFileSystem() {
    const content = await this.serializeStats();
    // Write content to the fs

  }

  isSameDay(dateTime) {
    // Write code to compare "dateTime" with current time.
    // Return true, if "dateTime" is same day as "current time"
  }

  async update(users, posts, comments) {
    const stats = this.stats;
    const statsLength = stats.length;
    const stat = { dateTime: Date.now(), users, posts, comments };
    if(statsLength.length === 0) {
      stats.push(stat);
    }
    else if(this.isSameDay(stats[statsLength-1].dateTime) === true) {
      stats[statsLength-1] = stat;
    }
    else {
      stats.push(stat);
    }
    await this.syncWithFileSystem();
  }

}

Finally in the request handler:

const statsManager = new StatsManager();
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()

  await statsManager.update(users, posts, comments);

  res.status(200).json({ updated: true })

})