function imgHandle(filePaths = {
path1: './src/images',
path2: './src/tempImg',
path3: '\src\images',
path4: '\src\tempImg'
}, isDeep = true, ignoreFile = ['common'], isdelDir = true) {
const fs = require('fs')
const path = require('path')
const filePath = path.resolve(filePaths.path1)
const tempImgPath = path.resolve(filePaths.path2)
const tinify = require('tinify')
tinify.key = 'VzjzXnvLyZncGtY4HzQFKlXst26mP68G'
if (isdelDir) {
delDir(tempImgPath)
}
if (!fs.existsSync(tempImgPath)) {
fs.mkdirSync(tempImgPath)
}
fileDisplay(filePath, tempImgPath)
function delDir(path) {
let files = [];
if (fs.existsSync(path)) {
files = fs.readdirSync(path);
files.forEach((file, index) => {
let curPath = path + "/" + file;
if (fs.statSync(curPath).isDirectory()) {
delDir(curPath);
} else {
fs.unlinkSync(curPath);
}
});
fs.rmdirSync(path);
}
}
async function compressionImg(imgsPath, tinifyImgsPath) {
if (!tinifyImgsPath) return
fs.readdir(imgsPath, (err, files) => {
if (!err) {
files.forEach((fileName, index) => {
fs.stat(imgsPath + "/" + fileName, (err, stats) => {
if (err) {
return console.err(err)
} else {
const isFile = stats.isFile()
if (isFile && /.(gif|jpg|jpeg|png|GIF|JPG|PNG|pdf|PDF)$/.test(fileName)) {
tinify.fromFile(path.join(imgsPath, fileName))
.toFile(path.join(tinifyImgsPath, fileName))
.then(() => {
console.log('tinify ok:%s', fileName);
})
.catch((err) => {
console.log('tinify err:%s', err);
});
}
}
});
})
}
});
}
async function fileDisplay(filePath, tempImgPath) {
await compressionImg(filePath, tempImgPath)
return fs.readdir(filePath, function (err, files) {
if (err) {
console.warn(err)
} else {
files.map(fileName => {
if (ignoreFile.includes(fileName)) return
const filedir = path.join(filePath, fileName)
fs.stat(filedir, async function (eror, stats) {
if (eror) {
console.warn('获取文件stats失败')
} else {
const isFile = stats.isFile()
const isDir = stats.isDirectory()
if (isFile) return
if (isDir) {
const tempImg1 = filePath.replace(filePaths.path3, filePaths.path4)
const tempImg2 = filedir.replace(filePaths.path3, filePaths.path4)
if (!fs.existsSync(tempImg2)) {
fs.mkdirSync(path.join(tempImg1, fileName))
}
await compressionImg(filedir, tempImg2)
if(isDeep){
fileDisplay(filedir)
}
}
}
})
return fileName
})
}
})
}
}
exports.imgHandle = imgHandle