
How to Compress Images with Sharp in Node.js
Sohail Bhatti / September 17, 2025
How to Compress Images with Sharp in Node.js
Optimizing images is crucial for improving website performance, reducing load times, and saving bandwidth. Sharp is a powerful Node.js library that allows you to process and compress images efficiently.
Follow this step-by-step guide to compress images using Sharp.
Step 1: Install Sharp
Install Sharp in your Node.js project:
npm install sharp
Step 2: Create an Image Compression Script
You can use Sharp to compress images like JPEG, PNG, and WebP.
Below is an example script (compress-images.js) that recursively compresses images in a folder:
javascript filename="compress-images.js"
import fs from "fs";
import path from "path";
import sharp from "sharp";
// Function to recursively compress images in a folder
const compressDir = async (dir) => {
const files = fs.readdirSync(dir);
for (const file of files) {
const filePath = path.join(dir, file);
const stat = fs.statSync(filePath);
if (stat.isDirectory()) {
await compressDir(filePath); // recurse into subfolders
} else if (/\.(jpg|jpeg)$/i.test(file)) {
// Compress JPEGs
await sharp(filePath)
.jpeg({ quality: 70 }) // adjust quality
.toFile(filePath + ".tmp");
fs.renameSync(filePath + ".tmp", filePath);
console.log(`✅ Compressed JPEG: ${filePath}`);
} else if (/\.png$/i.test(file)) {
// Compress PNGs
await sharp(filePath)
.png({ quality: 70, compressionLevel: 9 })
.toFile(filePath + ".tmp");
fs.renameSync(filePath + ".tmp", filePath);
console.log(`✅ Compressed PNG: ${filePath}`);
} else if (/\.webp$/i.test(file)) {
// Compress WebP
await sharp(filePath)
.webp({ quality: 70 })
.toFile(filePath + ".tmp");
fs.renameSync(filePath + ".tmp", filePath);
console.log(`✅ Compressed WebP: ${filePath}`);
} else {
// Skip unsupported formats like SVG
console.log(`ℹ️ Skipped: ${filePath}`);
}
}
};
// Run on both folders
await compressDir("public/assets/images");
await compressDir("public/assets/svgs");
Step 3: Run the Script
Run the compression script with Node.js:
node compress-images.js
This will go through the specified folders and compress JPEG, PNG, and WebP files.
Step 4: Verify Compressed Images
Check your folders to confirm that the images have been compressed. You’ll notice reduced file sizes, which means faster load times and improved site performance.
Optional: Automate Compression
You can integrate this script into your build process by adding it to your package.json scripts:
"scripts": {
"compress:images": "node compress-images.js"
}
Now you can simply run:
npm run compress:images
Conclusion
Using Sharp in Node.js is an efficient way to compress images and optimize your website. With just a few lines of code, you can significantly improve site performance, reduce bandwidth costs, and enhance user experience.