Last active
May 10, 2017 14:30
-
-
Save fabLouis/daab137b010bd075f867f72fd4cc9ae9 to your computer and use it in GitHub Desktop.
Javascript file to encode images (png, jpg, jpeg) into WebP format
This file contains 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 path = require('path') | |
const exec = require("child_process").exec | |
const prompt = require('prompt') | |
// quality factor (0:small..100:big), default=75 | |
const WEBP_QUALITY_FACTOR = 80 | |
const WEBP_EXT = '.webp' | |
const TO_WEBP_DEFAULT_FOLDER = 'src/assets/images' | |
const FIELD_CHOICE = ['to WebP(1) ; from WebP(2)'] | |
const FIELD_FOLDER = [`folder (default: ${TO_WEBP_DEFAULT_FOLDER})`] | |
/** | |
* Allows to encode image into WebP format | |
* | |
* @param dir Folder to scan | |
*/ | |
var imagesToWebps = function (dir) { | |
fs.readdirSync(dir).forEach(function (file) { | |
file = dir + '/' + file | |
var stat = fs.statSync(file) | |
if (stat && stat.isDirectory()) { | |
imagesToWebps(file) | |
} else { | |
// Add another file image extension if needed | |
if (file.endsWith('.jpg') || file.endsWith('.jpeg') || file.endsWith('.png')) { | |
console.log(file) | |
var filename = path.basename(file, path.extname(file)) | |
var pathname = path.dirname(file) + '/' | |
// cwebp encoder command: https://developers.google.com/speed/webp/docs/cwebp | |
var cmd = `cwebp -q ${WEBP_QUALITY_FACTOR} ${file} -o ${pathname}${filename}${WEBP_EXT}` | |
// console.log(' ' + cmd); | |
exec(cmd, (error, stdout, stderr) => { | |
if (error) { | |
console.log(' stderr:' + stderr) | |
} else { | |
fs.unlink(file, function () { | |
console.log(` ${file} deleted`) | |
}); | |
} | |
}); | |
} | |
} | |
}); | |
}; | |
/** | |
* Main and first function to start this program | |
* | |
* @see https://developers.google.com/speed/webp/ | |
*/ | |
function start() { | |
prompt.start() | |
prompt.get(FIELD_CHOICE, function (err, promptValue) { | |
if (err) { | |
console.error(err) | |
} | |
switch (promptValue[FIELD_CHOICE[0]]) { | |
case "1": | |
prompt.get(FIELD_FOLDER, function (err, promptValue) { | |
if (err) console.error(err) | |
var value = promptValue[FIELD_FOLDER[0]] | |
if (value === "") { | |
value = TO_WEBP_DEFAULT_FOLDER | |
} | |
imagesToWebps(value); | |
}); | |
break; | |
case "2": | |
console.warn('TODO: decoder') | |
break; | |
} | |
}); | |
} | |
start() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment