Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
var fs = require('fs'), child_process = require('child_process');
var files = fs.readdirSync('.');
var largeFiles = files.filter(function(f) {
// check if the extension of f is jpg, png, or jpeg
if(['jpg','png','jpeg'].indexOf(f.split('.').slice(-1)[0].toLowerCase()) == -1)
return false;
// check that the file is greater than 600K
var stat = fs.statSync(f);
return !stat.isDirectory() && stat.size > 600000;
});
// format size for output purposes
function formatSize(fileSizeInBytes)
{
var i = -1;
var byteUnits = ['K', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y'];
do {
fileSizeInBytes = fileSizeInBytes / 1024;
i++;
} while (fileSizeInBytes > 1024);
return Math.max(fileSizeInBytes, 0.1).toFixed(1) + byteUnits[i];
};
console.log('found ' + largeFiles.length + ' files');
var numCompleted = 0;
largeFiles.forEach(function(file) {
var fileParts = file.split('.');
var oldStat = fs.statSync(file);
// the filename that the smaller file will be saved to
var newFile = fileParts.slice(0, fileParts.length - 1).join('.') + '.jpg';
// we use ffmpeg to resize
child_process.exec(
'ffmpeg -i "' + file + '" -vf scale=1000:-1 -y -q:v 2 "' + newFile + '"',
{
cwd: process.cwd()
},
function(err, stdout, stderr)
{
if(err)
throw err;
// print new size
var newStat = fs.statSync(newFile);
console.log(file + ' (' + formatSize(oldStat.size) + ') -> ' + newFile + ' (' + formatSize(newStat.size) + ')');
// if the new file is different from the old file (didn't replace old file), delete old file
if(newFile.toLowerCase() != file.toLowerCase())
fs.unlinkSync(file);
// check if we've finished
numCompleted++;
if(numCompleted >= largeFiles.length)
{
console.log('done');
process.exit(0);
}
}
);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment