const fs = require('fs');
const readdir = require('recursive-readdir');
/*
Simple script that removes trailing "garbage" from detectable images' filenames (i.e. downloads via `wget -i`)
Eg. image1.jpg.123[1] ==> image1.jpg
*/
const dir = process.argv[2];
if (!dir) {
console.log('Please specify a directory to process - Aborting.');
return;
}
const img1 = /^.*\.(jpe?g|png|gif)$/i; // does it end with an image tag?
const img2 = /\.(jpe?g|png|gif)(.*)/i; // group the image tag with other parts
function renameFile(fileName) {
const matched = fileName.match(img2);
if (!matched) return;
const type = matched[1];
const cruft = matched[2];
let i = fileName.indexOf(cruft);
let goodName = fileName.substr(0, i);
// hack, just make sure it's a unique filename
i = goodName.indexOf(type);
goodName = fileName.substr(0, i) + '_.' + type; // eg. 1_.jpg
fs.renameSync(fileName, goodName);
console.log(fileName, ' --> ', goodName);
}
(async () => {
const fileNames = await readdir(dir);
fileNames.forEach(f => {
if (!img1.test(f)) renameFile(f);
});
})();