Optimize images from a Node.js script
By Flavio Copes
Learn how to optimize images from a Node.js script with sharp, converting a PNG to lossless webp and resizing or rotating it in just a few lines.
One tool I’ve been using to optimize images is sharp. The current release (0.35.x) needs Node.js 20.9 or newer, so any supported Node version works.
Install it in your project:
npm install sharp
Then import it:
import sharp from 'sharp'
Here’s how I used it to convert images to webp:
await sharp('image.png')
.webp({ lossless: true })
.toFile('image.webp')
For photographs, lossy WebP is usually much smaller than lossless WebP. You can resize the image, correct its orientation from EXIF metadata, and set a quality in the same pipeline:
await sharp('photo.jpg')
.rotate()
.resize({ width: 1600, withoutEnlargement: true })
.webp({ quality: 82 })
.toFile('photo.webp')
withoutEnlargement prevents a small source image from being scaled up. Keep the original until you have visually checked the output, especially when changing formats or using lossy compression.
If you want AVIF instead, swap the format step and keep the rest of the pipeline:
await sharp('photo.jpg')
.rotate()
.resize({ width: 1600, withoutEnlargement: true })
.avif({ quality: 50 })
.toFile('photo.avif')
To convert a whole folder, loop over the files. This turns every .jpg and .png in /Users/flavio/photos into WebP:
import { readdir } from 'node:fs/promises'
import sharp from 'sharp'
const folder = '/Users/flavio/photos'
const files = await readdir(folder)
for (const file of files) {
if (!/\.(jpe?g|png)$/i.test(file)) continue
const input = `${folder}/${file}`
const output = `${folder}/${file.replace(/\.[^.]+$/, '.webp')}`
await sharp(input)
.rotate()
.resize({ width: 1600, withoutEnlargement: true })
.webp({ quality: 82 })
.toFile(output)
console.log(file, '→', output)
}
If you just need to resize or compress a couple of images without writing a script, I made a browser-based image resizer tool — nothing gets uploaded anywhere.
Want me to talk about your product? You can sponsor this site.
Related posts about node: