I'm trying to convert every item in a block of folders to webp, and convert everything in a the folders titled "thumbnail" to 300x300 and to webp.
The directories go like this
folder-one > subfolder-one > thumbnails > thumbnailone.jpg
thumbnailtwo.jpg
imageone.jpg
imagetwo.jpg
subfolder-two > thumbnails > thumbnailone.jpg
thumbnailtwo.jpg
imageone.jpg
imagetwo.jpg
subfolder-three > thumbnails > thumbnailone.jpg
thumbnailtwo.jpg
imageone.jpg
imagetwo.jpg
and there are 4 total folders.
Here's the code i've written. I'm not getting any error response but code is not working:(
const sharp = require('sharp');
const fs = require('fs')
const folders = ['folder-one','folder-two','folder-three','folder-four']
let i;
for (i = 0; i < folders.length; i++) {
fs.readdirSync(`${fruits[i]}`, function(err, data){
for (i = 0; i < data.length; i++) {
fs.readdirSync(`/${data[i]}`, function read(err, data){
for (i = 0; i < data.length; i++) {
sharp(`${data[i]}.jpg`)
.toFile(`${data[i]}.webp`, function(err) {
});
}
})
fs.readdirSync(`/${data[i]}/thumbnails`, function read(err, data){
sharp(`${data[i]}.jpg`)
.resize(300, 300)
.toFile(`${data[i]}.webp`, function(err) {
});
})
}
})
}
Thank you!
You're using fs.readdirSync
with the asynchronous callback style. Those should either be readdir
s and you should check the errors, or not use the callback style. See the docs .
Here are some examples on how to do this with each of the options ( fs.readdir
, fs.readdirSync
, and fs.promises.readdir
):
// using readdir
fs.readdir(dir, function (err, data) {
if (err) console.error(error)
// do things with data
})
// using readdirSync
try {
const data = fs.readdirSync(dir)
// do things with data
} catch (err) {
console.error(err)
}
// using the promisified version
const fs = require('fs/promises')
fs.readdir(dir)
.then((data) => { /* do things with data */ })
.catch((err) => { console.error(err) })
// or using async/await syntax
;(async () => {
try {
const data = fs.readdir(dir)
// do things with data
} catch (err) {
console.error(err)
}
})
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.