Skip to content

Instantly share code, notes, and snippets.

@idris95
Created September 9, 2023 06:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save idris95/b3cea957be1512082678e0e18e20d0bb to your computer and use it in GitHub Desktop.
Save idris95/b3cea957be1512082678e0e18e20d0bb to your computer and use it in GitHub Desktop.
A node js script to convert jpg, jpeg, and png format images to webp
const sharp = require('sharp');
const fs = require('fs');
const path = require('path');
// Define the input and output directories
const inputDir = './input';
const outputDir = './output';
// Create the output directory if it doesn't exist
if (!fs.existsSync(outputDir)) {
fs.mkdirSync(outputDir);
}
// Function to convert an image to WebP format
function convertToWebP(inputFilePath, outputFilePath) {
sharp(inputFilePath)
.webp()
.toFile(outputFilePath, (err, info) => {
if (err) {
console.error(`Error converting ${inputFilePath} to WebP: ${err}`);
} else {
console.log(`Converted ${inputFilePath} to WebP at ${outputFilePath}`);
}
});
}
// Read the files in the input directory
fs.readdir(inputDir, (err, files) => {
if (err) {
console.error(`Error reading input directory: ${err}`);
return;
}
// Filter only JPG and PNG files
const imageFiles = files.filter((file) => /\.(jpg|jpeg|png)$/i.test(file));
// Convert each image to WebP format
imageFiles.forEach((file) => {
const inputFilePath = path.join(inputDir, file);
const outputFilePath = path.join(
outputDir,
path.basename(file, path.extname(file)) + '.webp'
);
convertToWebP(inputFilePath, outputFilePath);
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment