基于tinify对图片进行批量压缩(二)

165 阅读1分钟
/* eslint-disable */
/**
 * @description 批量deep压缩文件
 * @param filePaths 路径对象
 * @param path1 需要压缩文件的路径,默认值:'./src/images'
 * @param path2 压缩文件生成的路径,默认值:'./src/tempImg'
 * @param path3 需要压缩文件上下级目录,默认值:'\src\images'
 * @param path4 压缩文件上下级目录,默认值:'\src\tempImg'
 * @param isDeep 是否深度压缩,默认值:true
 * @param ignoreFile 忽略文件夹,默认值:['common']
 * @param isdelDir 删除生成文件夹,默认值:true
 */
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,可通过注册获取
    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