Skip to content

Instantly share code, notes, and snippets.

@rioki
Last active October 26, 2023 17:58
Show Gist options
  • Save rioki/3713041 to your computer and use it in GitHub Desktop.
Save rioki/3713041 to your computer and use it in GitHub Desktop.
Automatically sync two directories with node.js.
var fs = require("fs");
var path = require("path");
var configFile = "autosync.json";
if (process.argv.length == 3) {
configFile = process.argv[2];
}
var config = JSON.parse(fs.readFileSync(configFile, "UTF-8"));
config.repatterns = [];
for (var i = 0; i < config.patterns.length; i++) {
config.repatterns.push(new RegExp(config.patterns[i], "i"));
}
console.log("------------------------------------------");
console.log("Autosync - Revision 0");
console.log("------------------------------------------");
console.log("Source: " + config.source);
console.log("Destination: " + config.destination);
console.log("Patterns: " + config.repatterns);
console.log("------------------------------------------");
function dups(a, b) {
var i = 0;
var j = 0;
var r = [];
a.sort();
b.sort();
while (i < a.length && j < b.length) {
if (a[i] == b[j]) {
r.push(a[i]);
i++;
j++;
}
else {
if (a[i] < b[j])
i++;
else
j++;
}
}
return r;
}
function copy(source, dest, cb) {
var rs = fs.createReadStream(source);
var ws = fs.createWriteStream(dest);
rs.pipe(ws);
ws.on("end", cb);
}
function watchFile(source, dest) {
var file = path.basename(source);
console.log("watching " + file);
fs.watchFile(source, function (curr, prev) {
copy(source, dest, function (err) {
if (err) {
console.log("failed to copy " + file);
// TODO retry?
}
else {
console.log("copied " + file);
}
});
});
}
fs.readdir(config.source, function (err, sourceFiles) {
if (err) throw err;
fs.readdir(config.destination, function (err, destFiles) {
if (err) throw err;
var files = dups(sourceFiles, destFiles);
for (var i = 0; i < files.length; i++) {
for (var j = 0; j < config.repatterns.length; j++) {
if (files[i].match(config.repatterns[j])) {
var sourceFile = path.join(config.source, files[i]);
var destFile = path.join(config.destination, files[i]);
watchFile(sourceFile, destFile);
}
}
}
});
});
{
"source": "D:\\Devel\\MyProject\\_bin\\release",
"destination": "C:\\Program Files\\MyPorject\\bin",
"patterns": [
".dll$",
".exe$",
".pdb$"
]
}
@jerrylau91
Copy link

really helpful

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment