const fs = require('fs');
const path = require('path');
const { exec } = require('child_process');
const schedule = require('node-schedule');
/**
* Backs up files containing strings.
* @param {string[]} filePaths Array of file paths to backup.
* @param {string} backupDir Directory to store backups.
* @param {object} options Backup options.
* @param {number} options.retries Number of retry attempts.
* @param {number} options.retryDelay Delay between retries in milliseconds.
*/
function backupFiles(filePaths, backupDir, options = {}) {
const retries = options.retries || 3;
const retryDelay = options.retryDelay || 5000;
if (!fs.existsSync(backupDir)) {
fs.mkdirSync(backupDir, { recursive: true });
}
async function backupFile(filePath) {
for (let attempt = 0; attempt < retries; attempt++) {
try {
const fileName = path.basename(filePath);
const backupFilePath = path.join(backupDir, `backup_${fileName}_${Date.now()}.txt`);
// Read the file content
const fileContent = fs.readFileSync(filePath, 'utf8');
// Write the content to the backup file
fs.writeFileSync(backupFilePath, fileContent);
console.log(`Backup created for ${filePath} at ${backupFilePath}`);
return true; // Success
} catch (error) {
console.error(`Backup failed for ${filePath} (attempt ${attempt + 1}): ${error.message}`);
if (attempt < retries - 1) {
await new Promise(resolve => setTimeout(resolve, retryDelay)); // Wait before retrying
} else {
console.error(`Backup failed for ${filePath} after ${retries} attempts.`);
return false; // Failure
}
}
}
}
// Process each file path
const promises = filePaths.map(backupFile);
await Promise.all(promises);
}
/**
* Schedules the backup job.
* @param {string[]} filePaths Array of file paths to backup.
* @param {string} backupDir Directory to store backups.
* @param {string} scheduleExpression Cron expression for scheduling.
*/
function scheduleBackup(filePaths, backupDir, scheduleExpression) {
schedule.scheduleJob(scheduleExpression, () => {
console.log('Running scheduled backup...');
backupFiles(filePaths, backupDir);
});
}
module.exports = { backupFiles, scheduleBackup };
Add your comment