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

Image of Timescale

Timescale – the developer's data platform for modern apps, built on PostgreSQL

Timescale Cloud is PostgreSQL optimized for speed, scale, and performance. Over 3 million IoT, AI, crypto, and dev tool apps are powered by Timescale. Try it free today! No credit card required.

Try free

Top comments (0)

Retry later
👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay