Skip to content

Instantly share code, notes, and snippets.

@reyemtm
Created January 11, 2021 13:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save reyemtm/26105b803618c3e38e4f842a67598281 to your computer and use it in GitHub Desktop.
Save reyemtm/26105b803618c3e38e4f842a67598281 to your computer and use it in GitHub Desktop.
Node PNG or JPG to WebP
const fs = require('fs'),
path = require('path');
const sharp = require('sharp');
const ora = require("ora");
if (process.argv.length < 3) {
console.log("A relative or full directory path is required.")
return
}
const directory = process.argv[2]
const spinner = ora().start();
const walkSync = (dir, filelist = []) => {
fs.readdirSync(dir).forEach(file => {
filelist = fs.statSync(path.join(dir, file)).isDirectory() ?
walkSync(path.join(dir, file), filelist) :
filelist.concat(path.join(dir, file));
});
return filelist;
}
spinner.info("Collecting file list");
spinner.start()
const fileList = walkSync(directory);
const files = fileList.filter(f => {
return path.extname(f).toLowerCase() === ".png" || path.extname(f).toLowerCase() === ".jpg" || path.extname(f).toLowerCase() === ".jpeg"
});
// const files = JSON.parse(fs.readFileSync("files.json"))
// fs.writeFileSync("files.json", JSON.stringify(files))
spinner.succeed("Found " + files.length + " png or jpg files")
async function toWebp(imgFile) {
const ext = path.extname(imgFile)
const img = await sharp(imgFile)
.toFile(imgFile.replace(ext, ".webp"))
}
let x = 0;
files.forEach(async (file,i) => {
try {
await toWebp(file);
console.log(i, "of", files.length)
x = x + 1;
if (x === files.length) {
const text = "Completed " + files.length + " files!"
spinner.succeed(text)
}
}catch(error) {
console.log(error)
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment