A Node.js script that optimizes images to WebP format, providing excellent compression while maintaining high quality.
optimize-images.js/
├── input/ # Put your image folders here
│ ├── folder1/ # Your image folders
│ ├── folder2/ # Each folder contains images
│ └── ...
├── optimized/ # Optimized images will be saved here
├── optimize-images.js
├── package.json
├── .gitignore # Prevents input/ and optimized/ from being uploaded to Git
└── README.md
npm install- Create folders inside the
input/directory - Put your images (JPG, PNG, GIF, WebP) in those folders
- Example:
input/my-photos/,input/product-images/, etc.
node optimize-images.js- Optimized WebP images will be saved in the
optimized/folder - Each input folder will have a corresponding output folder
- Only optimized versions that are smaller than originals are saved
- WebP Output: Perfect for WordPress websites
- Smart Optimization: Only saves if file size is reduced
- Batch Processing: Processes all folders in input directory
- Quality Control: 85% quality (good balance for web)
- Detailed Reporting: Shows file sizes in KB and reduction percentages
# Set quality (0-100, default: 85)
set IMG_QUALITY=90
# Set format (webp, avif, jpeg, png, default: webp)
set IMG_FORMAT=webp
# Run with custom settings
set IMG_QUALITY=90 && node optimize-images.js# Use custom input and output folders
node optimize-images.js "path/to/input" "path/to/output"📁 Found 2 folders: my-photos, product-images
🔄 Processing folder: my-photos...
📁 [my-photos] Found 15 images to optimize
✅ photo1.jpg → photo1.webp: 2.1MB → 456.2KB (78.3% reduction, WEBP)
✅ photo2.jpg → photo2.webp: 1.8MB → 398.7KB (77.9% reduction, WEBP)
✔ [my-photos] Optimized 15/15 images → optimized\my-photos
📊 Total size: 28.5MB → 6.2MB (78.2% reduction)
⏱️ my-photos completed in 12.3s
🔄 Processing folder: product-images...
📁 [product-images] Found 8 images to optimize
✅ product1.png → product1.webp: 1.2MB → 234.1KB (80.5% reduction, WEBP)
✔ [product-images] Optimized 8/8 images → optimized\product-images
📊 Total size: 9.8MB → 1.9MB (80.6% reduction)
⏱️ product-images completed in 8.7s
🎉 All done!
- Smaller file sizes (25-35% smaller than JPEG)
- Better quality than JPEG at same file size
- Supports transparency like PNG
- Widely supported by modern browsers
- WordPress compatible (since WordPress 5.8)
- Faster page loading = better SEO
The .gitignore file ensures that:
input/folder is not uploaded to Git (your original images stay private)optimized/folder is not uploaded to Git (output files are generated locally)node_modules/is excluded (dependencies are installed locally)
sharp: High-performance image processing library- Built-in Node.js modules:
fs,path