Skip to content

Instantly share code, notes, and snippets.

@guipn
Last active January 2, 2016 04:39
Show Gist options
  • Save guipn/8252216 to your computer and use it in GitHub Desktop.
Save guipn/8252216 to your computer and use it in GitHub Desktop.
var fs = require('fs'),
cfg = JSON.parse(fs.readFileSync('respawn.json', { encoding: 'utf8' })),
now = new Date(),
t_stamp = now.getFullYear() + '-' +
(now.getMonth() + 1) + '-' +
now.getDate();
function copy(source, target) {
fs.createReadStream(source).pipe(fs.createWriteStream(target));
}
function echo(msg, indent) {
indent = indent || 1;
console.log(Array(indent + 1).join('\t') + msg);
}
function maybe_add_ts(path) {
return cfg.add_timestamp === true ?
path + ' ' + t_stamp :
path;
}
function prepare_backup_dir(path) {
if (!fs.existsSync(path)) {
fs.mkdirSync(path);
}
}
echo('\n\tStarting backups!\n\n');
cfg.targets.forEach(function (target) {
var backup_dir = cfg.backup_root_dir + target.backup_subdir,
filenames;
backup_dir = maybe_add_ts(backup_dir);
prepare_backup_dir(backup_dir);
echo('Backing up ' + target.source_dir + ' to ' + backup_dir + '...\n');
filenames = fs.readdirSync(target.source_dir).filter(function (name) {
var extMatch = name.match(/.+\.(.+)/);
return extMatch !== null &&
target.extension_blacklist.indexOf(extMatch[1]) === -1;
});
filenames.forEach(function (filename) {
var file_to_copy = target.source_dir + '\\' + filename,
target_path = backup_dir + '\\' + filename;
echo(file_to_copy + ' -> ' + target_path, 2);
copy(file_to_copy, target_path);
target.alternative_backup_dirs.forEach(function (alternative) {
alternative = maybe_add_ts(alternative);
prepare_backup_dir(alternative);
alternative += '\\' + filename;
echo(file_to_copy + ' -> ' + alternative + ' (alternative)', 3);
copy(file_to_copy, alternative);
});
});
echo('\n\n\tDone.\n');
});
{
"backup_root_dir": "C:\\",
"targets": [
{
"source_dir": ".",
"backup_subdir": "spawn",
"alternative_backup_dirs": [
"C:\\spawn2",
"C:\\spawn3"
],
"extension_blacklist": [
"xlsx", "txt"
]
}
],
"add_timestamp": true
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment