Skip to content

Instantly share code, notes, and snippets.

@LearnWebCode
Created October 1, 2024 19:00
Show Gist options
  • Save LearnWebCode/487ce9e078a49e98efba5df7659bff5b to your computer and use it in GitHub Desktop.
Save LearnWebCode/487ce9e078a49e98efba5df7659bff5b to your computer and use it in GitHub Desktop.
Convert all .jpg and .jpeg files in the current directory to webp instead using the sharp package from NPM
const sharp = require("sharp")
const fs = require("fs").promises
async function start() {
// create the converted-images folder if it does not exist yet
fs.mkdir("./converted-images", { recursive: true })
// create array of all files in current directory
const files = await fs.readdir("./")
// filter for only the .jpg and .jpeg files
const onlyJpgs = files.filter(file => {
return file.endsWith(".jpg") || file.endsWith(".jpeg")
})
// for each one convert it to webp
onlyJpgs.forEach(file => {
let newfilename
if (file.endsWith(".jpg")) {
newfilename = file.slice(0, -4) + ".webp"
}
if (file.endsWith(".jpeg")) {
newfilename = file.slice(0, -5) + ".webp"
}
jpg2webp(file, `converted-images/${newfilename}`)
})
}
start()
async function jpg2webp(input, output) {
try {
const inputBuffer = await fs.readFile(input)
const webpBuffer = await sharp(inputBuffer).webp().toBuffer()
// if you also want to resize the image then remove the
// line above this line and uncomment the line below
//const webpBuffer = await sharp(inputBuffer).resize({ width: 1024 }).webp().toBuffer()
await fs.writeFile(output, webpBuffer)
console.log(`${input} was converted.`)
} catch (error) {
console.error("There was an error:", error)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment