Skip to content

Instantly share code, notes, and snippets.

@xelaz
Last active September 5, 2022 07:27
Show Gist options
  • Save xelaz/f6041088d32a513d58c478060e1bc303 to your computer and use it in GitHub Desktop.
Save xelaz/f6041088d32a513d58c478060e1bc303 to your computer and use it in GitHub Desktop.
NodeJs resize and optimize images with sharp
const fs = require('fs');
const glob = require('glob');
const sharp = require('sharp');
const Promise = require('bluebird');
const successList = [];
const errorList = {};
glob("wp-content/uploads/**/*.+(jpeg|jpg)", function (er, files) {
Promise.resolve(files)
.mapSeries((file) => resize(file))
.then(() => Promise.fromCallback(function(cb) {
fs.writeFile('resize.log', JSON.stringify(errorList, null, 2) , cb);
})
.catch(function(err) {
errorList['write_log_to_file_error'] = err;
})
)
.then(function() {
console.log('------------------------------');
console.log('TOTAL:', files.length);
console.log('OKAY:', successList.length);
console.log('FAIL:', Object.keys(errorList).length);
});
});
function resize(file) {
return sharp(file)
.resize(1920, 1440)
.max()
.withoutEnlargement()
.toFormat('jpeg', { progressive: true, quality: 50 })
.toBuffer()
.then(buffer => Promise.fromCallback(cb => fs.writeFile(file, buffer, cb)))
.then(function() {
successList.push(file);
console.log('Okay:', file);
})
.catch(function(err) {
console.log('Fail:', file, '\n', err);
errorList[file] = { message: err.message, fileName: err.fileName, lineNumber: err.lineNumber };
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment