Created
May 26, 2023 08:40
-
-
Save vzakharov/64ed66dcca3d01faff5289154220f08a to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Syncs two folders together. If a file is added, updated, or deleted in the original folder, it will be added, updated, or deleted in the duplicate folder. Uses fs.watch() to watch for changes in the original folder, so make sure your OS supports it. | |
const fs = require('fs'); | |
const path = require('path'); | |
const originalFolder = process.argv[2]; | |
const duplicateFolder = process.argv[3]; | |
if (!originalFolder || !duplicateFolder) { | |
console.error('Usage: node sync.js <original_folder> <duplicate_folder>'); | |
process.exit(1); | |
} | |
function copyFolderSync(src, dest) { | |
if (!fs.existsSync(dest)) { | |
fs.mkdirSync(dest); | |
} | |
const entries = fs.readdirSync(src, { withFileTypes: true }); | |
for (const entry of entries) { | |
const srcPath = path.join(src, entry.name); | |
const destPath = path.join(dest, entry.name); | |
if (entry.isDirectory()) { | |
copyFolderSync(srcPath, destPath); | |
} else { | |
fs.copyFileSync(srcPath, destPath); | |
} | |
} | |
} | |
function watchFolder(folder) { | |
fs.watch(folder, { recursive: true }, (eventType, filename) => { | |
if (filename) { | |
const srcPath = path.join(originalFolder, filename); | |
const destPath = path.join(duplicateFolder, filename); | |
if (fs.existsSync(srcPath)) { | |
if (fs.lstatSync(srcPath).isDirectory()) { | |
copyFolderSync(srcPath, destPath); | |
} else { | |
fs.copyFileSync(srcPath, destPath); | |
} | |
} else { | |
fs.rmSync(destPath, { recursive: true, force: true }); | |
} | |
} | |
}); | |
} | |
copyFolderSync(originalFolder, duplicateFolder); | |
watchFolder(originalFolder); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment