DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’»

Cover image for File Backup NodeJS
Abayomi Ogunnusi
Abayomi Ogunnusi

Posted on

File Backup NodeJS

πŸ“š This short post demonstrates how to create an app that does the following:

Update a file and backup the old file.
If the file does not exist, create it
If the file exists, backup the old file and update the new file
If the backup file exists, delete it

app.post('/', async (req, res) => {
  const filePath = path.join(__dirname, 'data.txt');
  //backup path with format date to YYYYMM-DD--HH_mm
  const backupPath = path.join(
    __dirname,
    `data-${new Date()
      .toISOString()
      .replace(/:/g, '_')
      .replace(/-/g, '_')
      .replace(/\./g, '_')
      .replace('T', '--')}.txt`
  );

  if (fs.existsSync(filePath)) {
    fs.copyFileSync(filePath, backupPath);
    fs.unlinkSync(filePath);
  }
  fs.writeFileSync(filePath, req.body.note);
  // send the new file content back to the db
  const course = new Course({
    name: req.body.note,
  });
  await course.save();
  res.send('file written');
});
Enter fullscreen mode Exit fullscreen mode

Source code

Top comments (0)

πŸ‘‹ Hey, my name is Noah and I’m the one who set up this ad. My job is to get you to join DEV, so if you fancy doing me a favor, I’d love for you to create an account.

If you found DEV from searching around, here are a couple of our most popular articles on DEV: