Convert all JPGs and PNGs in a folder to WEBP and AVIF with Node.js and Sharp

One of the easiest ways to convert all JPG and PNG images in a folder to WEBP and AVIF is to use the Sharp library.

Let’s get straight to the point. We will need to install sharp and glob.

npm install --save glob sharp

With that done, we now need to write a relatively simple loop to find all images and convert them to WEBP and AVIF. We will also make sure that our script can accept any folder path to process the images. You will see that in the folderPath declaration.

const sharp = require('sharp');
const glob = require('glob');
const path = require('path');

const folderPath = path.resolve(process.argv[2] || __dirname);
const imageExtensions = ['.png', '.jpg'];
const outputFormats = ['webp', 'avif'];

const convertImages = async () => {
    try {
        console.log(`Converting all images in ${folderPath}`);
        const files = await new Promise((resolve, reject) => {
            glob(`${folderPath}/**/*{${imageExtensions.join(',')}}`, (err, files) => {
                if (err) reject(err);
                else resolve(files);
            });
        });

        for (const file of files) {
            const fileExt = path.extname(file);
            if (imageExtensions.includes(fileExt)) {
                for (const outputFormat of outputFormats) {
                    const outputFile = path.join(path.dirname(file), path.basename(file, fileExt) + '.' + outputFormat);
                    await sharp(file)
                        .toFormat(outputFormat)
                        .toFile(outputFile);    
                    console.log(`${file} was converted to ${outputFile}`);
                }
            }
        }
    } catch (err) {
        console.error(err);
    }
};

convertImages();

Wrap this into any js file (for ex. convert.js), and then run it with node convert.js or node convert.js /some/folder/with/images.

It’s pretty short, but handles finding images, changing the extension, converting, and saving. Going further, you can wrap this up into a cross-platform Docker image to be able to run this converter from any device or location.

Resources


Did you know that I made an in-browser image converter, where you can convert your images without uploading them anywhere? Try it out and let me know what you think. It's free.

Leave a Comment

Your email address will not be published. Required fields are marked *