Last active
September 5, 2022 07:27
-
-
Save xelaz/f6041088d32a513d58c478060e1bc303 to your computer and use it in GitHub Desktop.
NodeJs resize and optimize images with sharp
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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