Skip to content

Instantly share code, notes, and snippets.

@jboulhous
Last active October 23, 2017 15:10
Show Gist options
  • Save jboulhous/cd5d1e701bd5929969636138a9830249 to your computer and use it in GitHub Desktop.
Save jboulhous/cd5d1e701bd5929969636138a9830249 to your computer and use it in GitHub Desktop.
Archive downloads in YYYY-MM folders
/*
call this way:
node script.js /path/to/Downloads/folder
*/
const fs = require('fs');
const path = require('path');
function now () { return new Date() }
function folderName (date = now()) {
const year = date.getUTCFullYear();
const month = date.getUTCMonth() + 1;
const directory = `${year}-${ ( (month < 10) ? ('0' + month) : month ) }`;
return directory;
}
function buildFile (filename, cwd) {
const filepath = path.join(cwd, filename)
const stat = fs.statSync(filepath);
const birthtime = stat.birthtime;
// const year = getYear(birthtime);
// const month = getMonth(birthtime);
// const directory = `${year}-${startWithZero(month + 1)}`;
const directory = folderName(birthtime);
return {
filename,
filepath,
directory
}
}
function ensureFolders (results) {
for (dir in results) {
if (!fs.existsSync(dir)){
fs.mkdirSync(dir);
}
}
}
function moveFilesToFolders (results) {
for (dir in results) {
results[dir].forEach(file => {
fs.renameSync(file.filepath, path.join(dir, file.filename));
});
}
}
function main (cwd) {
const now = new Date();
// const fyear = getYear(now);
// const fmonth = getMonth(now);
// const thismonth = `${fyear}-${startWithZero(fmonth + 1)}`;
const thismonth = folderName(now);
const files = fs.readdirSync(cwd);
const results = {};
let i = 0;
files.forEach(file => {
// const filepath = path.join(cwd, file);
const File = buildFile(file, cwd);
if ( (file != "desktop.ini") && (file != File.directory) && (thismonth != File.directory) && !(/^[0-9]{4}-[0-9]{2}$/.test(file)) ) {
const directory = path.join(cwd, File.directory);
if (!results[directory]) results[directory] = [];
results[directory].push(File);
i++;
}
});
console.log(`${i} / ${files.length} needs to be moved`)
for (key in results) {
console.log(key, ':');
results[key].forEach(f => console.log(' ', f.filepath));
}
ensureFolders(results);
moveFilesToFolders(results);
}
const downloads = process.argv[2];
downloads && main(downloads);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment