Skip to content

Instantly share code, notes, and snippets.

@obedparla
Created April 15, 2024 08:07
Show Gist options
  • Save obedparla/7792b1649ee6456ff69c99b4ca46b603 to your computer and use it in GitHub Desktop.
Save obedparla/7792b1649ee6456ff69c99b4ca46b603 to your computer and use it in GitHub Desktop.
const fs = require('fs');
const path = require('path');
const tinify = require('tinify');
require('dotenv').config()
tinify.key = process.env.API;
// Define the directories.
const inputDir = './images';
const outputDir = './optimized';
// Read all files in the input directory.
fs.readdir(inputDir, (err, files) => {
if (err) {
console.error("Error reading the input directory:", err);
return;
}
files.forEach(file => {
if (path.extname(file) === '.png' || path.extname(file) === '.jpeg') {
const inputPath = path.join(inputDir, file);
const outputPath = path.join(outputDir, path.basename(file, '.png') + '.webp');
const source = tinify.fromFile(inputPath);
// will only return the smallest one between webp and png
const converted = source.convert({type:["image/webp","image/png"]});
const extension = converted.result().extension();
extension.then(ext => {
converted.toFile(outputPath, (err) => {
if (err) {
console.error("Error processing file:", file, err);
} else {
console.log("Successfully converted:", file, "to", outputPath);
}
});
})
}
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment