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)