在NodeJS中,如何使用for循环将fs和sharp混合目录中的文件转换为webp



我正试图将文件夹块中的每一项都转换为webp,并将文件夹中标题为"缩略图";至300x300和至webp。

目录如下


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 

并且总共有4个文件夹。

这是我写的代码。我没有得到任何错误响应,但代码不起作用:(

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) {
});
})
}
})
}

谢谢!

您使用的是带有异步回调样式的fs.readdirSync。这些应该是readdirs,并且您应该检查错误,或者不使用回调样式。请参阅文档。

以下是关于如何使用每个选项(fs.readdirfs.readdirSyncfs.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)
}
})

最新更新