Last active
August 28, 2024 09:55
-
-
Save tomhermans/5e279c2597cdd1ca0517b0e991ae3715 to your computer and use it in GitHub Desktop.
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
/** | |
This Node.js script converts WebP images to either PNG or JPG format. | |
It's a command-line tool that processes all WebP files in a specified input folder and saves the converted images in a new output folder with a unique timestamp. | |
more info below: | |
*/ | |
const fs = require('fs'); | |
const path = require('path'); | |
const sharp = require('sharp'); | |
const readline = require('readline'); | |
const rl = readline.createInterface({ | |
input: process.stdin, | |
output: process.stdout | |
}); | |
function askQuestion(query) { | |
return new Promise(resolve => rl.question(query, resolve)); | |
} | |
async function main() { | |
// Ask for input folder | |
const inputFolder = await askQuestion('Enter the input folder path (press Enter for current folder): ') || '.'; | |
// Ask for output format | |
let outputFormat; | |
do { | |
outputFormat = await askQuestion('Enter the output format (jpg or png): ').then(ans => ans.toLowerCase()); | |
} while (outputFormat !== 'jpg' && outputFormat !== 'png'); | |
// Create output folder | |
const timestamp = new Date().toISOString().replace(/[:.-]/g, '_'); | |
const outputFolder = path.join('.', `output_${timestamp}`); | |
fs.mkdirSync(outputFolder, { recursive: true }); | |
console.log(`Input folder: ${inputFolder}`); | |
console.log(`Output folder: ${outputFolder}`); | |
console.log(`Output format: ${outputFormat}`); | |
// Process WebP files | |
fs.readdir(inputFolder, (err, files) => { | |
if (err) { | |
console.error('Error reading input folder:', err); | |
rl.close(); | |
return; | |
} | |
const webpFiles = files.filter(file => path.extname(file).toLowerCase() === '.webp'); | |
console.log(`Found ${webpFiles.length} WebP files to convert.`); | |
if (webpFiles.length === 0) { | |
console.log('No WebP files found to process.'); | |
rl.close(); | |
return; | |
} | |
let processedCount = 0; | |
let errorCount = 0; | |
webpFiles.forEach(file => { | |
const inputPath = path.join(inputFolder, file); | |
const outputFileName = `${path.parse(file).name}.${outputFormat}`; | |
const outputPath = path.join(outputFolder, outputFileName); | |
console.log(`Converting: ${file}`); | |
sharp(inputPath) | |
.toFormat(outputFormat) | |
.toFile(outputPath) | |
.then(() => { | |
console.log(`Successfully converted: ${file} -> ${outputFileName}`); | |
processedCount++; | |
if (processedCount + errorCount === webpFiles.length) { | |
console.log(`\nConversion complete. ${processedCount} files converted, ${errorCount} errors.`); | |
rl.close(); | |
} | |
}) | |
.catch(err => { | |
console.error(`Error converting ${file}:`, err); | |
errorCount++; | |
if (processedCount + errorCount === webpFiles.length) { | |
console.log(`\nConversion complete. ${processedCount} files converted, ${errorCount} errors.`); | |
rl.close(); | |
} | |
}); | |
}); | |
}); | |
} | |
main(); | |
/** | |
Features | |
Converts WebP images to PNG or JPG format | |
Allows user to specify input folder | |
Lets user choose between PNG or JPG output format | |
Creates a unique timestamped output folder for each run | |
Provides detailed console logging of the conversion process | |
Requirements | |
Node.js | |
Sharp library (npm install sharp) | |
Usage | |
Ensure you have Node.js installed and the Sharp library is installed in your project folder. | |
Save the script as webpconvert.js in your project folder. | |
Open a terminal or command prompt and navigate to the folder containing the script. | |
Run the script with: | |
Copynode webpconvert.js | |
Follow the prompts: | |
Enter the input folder path (or press Enter to use the current folder) | |
Choose the output format (jpg or png) | |
The script will process all WebP files in the input folder and save the converted images in a new output folder (e.g., output_2024_08_28T12_30_45_678Z). | |
How It Works | |
The script uses the readline module to prompt the user for input. | |
It creates a uniquely named output folder using the current timestamp. | |
It reads all files in the specified input folder and filters for WebP files. | |
Using the Sharp library, it converts each WebP file to the chosen format (PNG or JPG). | |
Converted files are saved in the output folder with the same name but new extension. | |
The script provides console logging for each file processed and a summary at the end. | |
Notes | |
The script only processes files with the .webp extension. | |
If no WebP files are found in the input folder, the script will notify the user and exit. | |
Any errors during the conversion process are logged to the console. | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment