Created
February 12, 2021 17:44
-
-
Save reyemtm/26f3e2d2946ce409ed003b9f814c5295 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 = []) => { | |
try { | |
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; | |
}catch(err) { | |
if (!fs.existsSync(dir)) { | |
spinner.fail("Directory does not exist!") | |
process.exit() | |
}else{ | |
spinner.fail("An error occurred!") | |
throw new Error(err) | |
} | |
} | |
} | |
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") | |
// spinner.start() | |
// process.exit() | |
async function toWebp(imgFile) { | |
const ext = path.extname(imgFile) | |
const img = await sharp(imgFile) | |
.toFile(imgFile.replace(ext, ".webp")) | |
} | |
let x = 0; | |
// for (let i = 0; i < files.length; i++) { | |
// let file = files[i] | |
// await toWebp(file); | |
// console.log(i) | |
// x = x - 1; | |
// if | |
// } | |
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