šŸŽ Checkout my Learn React by Making a Game course and get 1 month Free on Skillshare!

Node.js script for converting images to Webp and rename

As I need to convert almost every day some images for this blog to the Webp format decided to create a small Node.js to automate the task.

Examined some Javascript libs that do the image conversion to Webp and ended up with a short list made of sharp and imagemin. I've picked sharp as it is updated more often.

The scrip will do the following:

  • ask for a name for the files. If that name will be provided it will rename the files as name 0.webp, name 1.webp and so on. If the name is not provided it will keep the initial name of the files
  • will look just for the png and jpeg files from the ./INPUT folder
  • it will clear the contents of the './OUTPUT' folder
  • will convert all the images from the ./INPUT folder into webp files and store them in the './OUTPUT'

Below you can check out the full code of the script:

// Importing required libraries
const sharp = require('sharp')
const fs = require('fs')
const path = require('path')
const prompt = require('prompt-sync')()

// Define output and input directories
const OUTPUT_DIR = './OUTPUT'
const INPUT_DIR = './INPUT'

// Prompt user for a new file name pattern
const nPattern = prompt('Rename files to (none for the inital name):');

// If output directory exists, remove it and its contents
if (fs.existsSync(OUTPUT_DIR)){
    fs.rmSync(OUTPUT_DIR, { recursive: true, force: true })
}

// Create the output directory
fs.mkdirSync(OUTPUT_DIR)

// Define a function to convert image files to WebP format
let imgs = []
const convertToWebp = (img, index) => {
    // Define the name of the new WebP file
    const imgName = nPattern ? `${nPattern} ${index}` : path.parse(img).name
    // Use sharp to convert the image to WebP format and save it to the output directory
    sharp(`${INPUT_DIR}/${img}`)
        .webp()
        .toFile(`${OUTPUT_DIR}/${imgName}.webp`);
}

// Read the input directory and filter for image files (PNG, JPG, JPEG)
fs.readdir(INPUT_DIR, (err, files) => {
    imgs = files.filter(file => {
        const ext = path.extname(file).toLowerCase()
        return (ext === '.png') || (ext === '.jpg') || (ext === '.jpeg')
    })
    // For each image file found, call the convertToWebp function
    imgs.forEach ((img, i) => convertToWebp(img, i))
})

And here is the link to the github repository.

šŸ“– Frontend Odyssey: 25 projects in 100 days

Learn how to build production-ready web applications. Dive in with 25 projects with project briefs and wireframes!

  • ā­ļø 25+ React & JS projects
  • ā­ļø 100+ Interview questions
  • ā­ļø ChatGPT for developers
  • ā­ 50+ Project Ideas

šŸ“– Frontend Odyssey: 25 projects in 100 days

Learn how to build production-ready web applications. Dive in with 25 projects with project briefs and wireframes!

  • ā­ļø 25+ React & JS projects
  • ā­ļø 100+ Interview questions
  • ā­ļø ChatGPT for developers
  • ā­ 50+ Project Ideas

Leave a Reply

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