const fs = require('fs');
const path = require('path');
const filePath = path.resolve('./temp');
const tinify = require('tinify');
const { spawn } = require('child_process')
tinify.key = 'VzjzXnvLyZncGtY4HzQFKlXst26mP68G';
const run = async (command) => {
const [cmd, ...args] = command.split(' ')
return new Promise((resolve, reject) => {
const app = spawn(cmd, args, {
cwd: path.resolve('./'),
stdio: 'inherit',
shell: true
})
app.on('close', resolve)
})
}
async function compressionImg(imgsPath, tinifyImgsPath) {
if (!fs.existsSync(path.join(__dirname, `tinifyImgs`))) {
fs.mkdirSync(path.join(__dirname, `tinifyImgs`));
}
if (!fs.existsSync(tinifyImgsPath)) {
fs.mkdirSync(tinifyImgsPath);
}
fs.readdir(imgsPath, (err, files) => {
if (!err) {
files.forEach((fileName, index) => {
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);
});
})
}
});
}
const ignoreFile = ['node_modules', 'yarn.lock', '8-4']
const noDir = true
fileDisplay(filePath)
function fileDisplay(filePath, noDir = false) {
let imgFile = []
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, function (eror, stats) {
if (eror) {
console.warn('获取文件stats失败');
} else {
const isFile = stats.isFile();
const isDir = stats.isDirectory();
if (isFile) {
compressionImg(filedir, path.join(__dirname, `tinifyImgs`))
}
if (isDir) {
if (noDir) {
return
}
imgFile.push(filedir)
compressionImg(filedir, path.join(__dirname, `tinifyImgs\${fileName}`))
console.log('文件夹:', filedir, fileName)
fileDisplay(filedir);
}
}
})
return fileName
})
}
});
}