1. const fs = require('fs');
  2. const path = require('path');
  3. const { exec } = require('child_process');
  4. const schedule = require('node-schedule');
  5. /**
  6. * Backs up files containing strings.
  7. * @param {string[]} filePaths Array of file paths to backup.
  8. * @param {string} backupDir Directory to store backups.
  9. * @param {object} options Backup options.
  10. * @param {number} options.retries Number of retry attempts.
  11. * @param {number} options.retryDelay Delay between retries in milliseconds.
  12. */
  13. function backupFiles(filePaths, backupDir, options = {}) {
  14. const retries = options.retries || 3;
  15. const retryDelay = options.retryDelay || 5000;
  16. if (!fs.existsSync(backupDir)) {
  17. fs.mkdirSync(backupDir, { recursive: true });
  18. }
  19. async function backupFile(filePath) {
  20. for (let attempt = 0; attempt < retries; attempt++) {
  21. try {
  22. const fileName = path.basename(filePath);
  23. const backupFilePath = path.join(backupDir, `backup_${fileName}_${Date.now()}.txt`);
  24. // Read the file content
  25. const fileContent = fs.readFileSync(filePath, 'utf8');
  26. // Write the content to the backup file
  27. fs.writeFileSync(backupFilePath, fileContent);
  28. console.log(`Backup created for ${filePath} at ${backupFilePath}`);
  29. return true; // Success
  30. } catch (error) {
  31. console.error(`Backup failed for ${filePath} (attempt ${attempt + 1}): ${error.message}`);
  32. if (attempt < retries - 1) {
  33. await new Promise(resolve => setTimeout(resolve, retryDelay)); // Wait before retrying
  34. } else {
  35. console.error(`Backup failed for ${filePath} after ${retries} attempts.`);
  36. return false; // Failure
  37. }
  38. }
  39. }
  40. }
  41. // Process each file path
  42. const promises = filePaths.map(backupFile);
  43. await Promise.all(promises);
  44. }
  45. /**
  46. * Schedules the backup job.
  47. * @param {string[]} filePaths Array of file paths to backup.
  48. * @param {string} backupDir Directory to store backups.
  49. * @param {string} scheduleExpression Cron expression for scheduling.
  50. */
  51. function scheduleBackup(filePaths, backupDir, scheduleExpression) {
  52. schedule.scheduleJob(scheduleExpression, () => {
  53. console.log('Running scheduled backup...');
  54. backupFiles(filePaths, backupDir);
  55. });
  56. }
  57. module.exports = { backupFiles, scheduleBackup };

Add your comment