在Linux上使用Node.js进行数据备份与恢复,通常涉及以下几个步骤:
你可以编写一个Node.js脚本来遍历文件系统并备份指定的文件或目录。以下是一个简单的示例:
const fs = require('fs');
const path = require('path');
const sourceDir = '/path/to/source';
const backupDir = '/path/to/backup';
function backupDirectory(source, destination) {
if (!fs.existsSync(destination)) {
fs.mkdirSync(destination, { recursive: true });
}
const files = fs.readdirSync(source);
files.forEach(file => {
const sourcePath = path.join(source, file);
const destinationPath = path.join(destination, file);
if (fs.statSync(sourcePath).isDirectory()) {
backupDirectory(sourcePath, destinationPath);
} else {
fs.copyFileSync(sourcePath, destinationPath);
}
});
}
backupDirectory(sourceDir, backupDir);
console.log('Backup completed successfully!');
你可以使用Linux的cron定时任务来定期运行备份脚本。例如,每天凌晨2点运行备份脚本:
0 2 * * * /usr/bin/node /path/to/backup-script.js
你可以编写一个Node.js脚本来遍历备份目录并将文件复制回原始位置。以下是一个简单的示例:
const fs = require('fs');
const path = require('path');
const backupDir = '/path/to/backup';
const sourceDir = '/path/to/source';
function restoreDirectory(source, destination) {
if (!fs.existsSync(destination)) {
fs.mkdirSync(destination, { recursive: true });
}
const files = fs.readdirSync(source);
files.forEach(file => {
const sourcePath = path.join(source, file);
const destinationPath = path.join(destination, file);
if (fs.statSync(sourcePath).isDirectory()) {
restoreDirectory(sourcePath, destinationPath);
} else {
fs.copyFileSync(sourcePath, destinationPath);
}
});
}
restoreDirectory(backupDir, sourceDir);
console.log('Restore completed successfully!');
你可以使用Linux的cron定时任务来定期运行恢复脚本。例如,每天凌晨3点运行恢复脚本:
0 3 * * * /usr/bin/node /path/to/restore-script.js
通过以上步骤,你可以在Linux上使用Node.js进行数据备份与恢复。