Skip to content

Instantly share code, notes, and snippets.

@kj800x
Created September 8, 2024 01:48
Show Gist options
  • Save kj800x/ee2a5d7b5bf056a4525e6a18fc94dee0 to your computer and use it in GitHub Desktop.
Save kj800x/ee2a5d7b5bf056a4525e6a18fc94dee0 to your computer and use it in GitHub Desktop.
~/src auto archiver
// Scan CWD for directories modified longer than 365 days ago and move them to a new directory based on the current date in the archive directory.
// No dependencies, so only built-in modules are used.
// Just stick this in a directory and `node autoarchive.js`.
const fs = require('fs');
const path = require('path');
function leftPad(num, len) {
return num.toString().padStart(len, '0');
}
const cwd = process.cwd();
const now = new Date();
const nowYear = now.getFullYear();
const nowMonth = leftPad(now.getMonth() + 1, 2);
const nowDay = leftPad(now.getDate(), 2);
const nowDate = `${nowYear}-${nowMonth}-${nowDay}`;
const archiveDir = path.join(cwd, 'archive');
const archiveSubDir = path.join(archiveDir, nowDate)
const SKIP_DIRS = ['archive'];
if (!fs.existsSync(archiveDir)) {
fs.mkdirSync(archiveDir);
}
fs.readdir(cwd, (err, files) => {
if (err) {
console.error(err);
return;
}
files.forEach(file => {
const stats = fs.statSync(file);
const mtime = stats.mtime;
const diff = now - mtime;
const diffDays = diff / (1000 * 60 * 60 * 24);
const diffYears = diffDays / 365;
if (stats.isDirectory()) {
if (SKIP_DIRS.includes(file)) {
return;
}
if (diffDays > 365) {
console.log(`(${diffYears.toFixed(2)} years stale) Moving: ${file}`);
if (!fs.existsSync(archiveSubDir)) {
fs.mkdirSync(archiveSubDir);
}
fs.rename(file, path.join(archiveSubDir, file), err => {
if (err) {
console.error(err);
}
});
} else {
console.log(`(${diffYears.toFixed(2)} years stale) Keeping: ${file}`);
}
}
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment