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

Heroku

Simplify your DevOps and maximize your time.

Since 2007, Heroku has been the go-to platform for developers as it monitors uptime, performance, and infrastructure concerns, allowing you to focus on writing code.

Learn More

Top comments (0)

The Most Contextual AI Development Assistant

Pieces.app image

Our centralized storage agent works on-device, unifying various developer tools to proactively capture and enrich useful materials, streamline collaboration, and solve complex problems through a contextual understanding of your unique workflow.

👥 Ideal for solo developers, teams, and cross-company projects

Learn more

👋 Kindness is contagious

Discover a treasure trove of wisdom within this insightful piece, highly respected in the nurturing DEV Community enviroment. Developers, whether novice or expert, are encouraged to participate and add to our shared knowledge basin.

A simple "thank you" can illuminate someone's day. Express your appreciation in the comments section!

On DEV, sharing ideas smoothens our journey and strengthens our community ties. Learn something useful? Offering a quick thanks to the author is deeply appreciated.

Okay