1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46
| const fs = require('fs'); const path = require('path'); const tinify = require('tinify');
tinify.key = '你的KEY';
async function compressFiles(dir, blackDirs = []) { const files = fs.readdirSync(dir); for (let i = 0; i < files.length; i++) { const file = files[i]; const filePath = path.join(dir, file); const stat = fs.statSync(filePath);
if (stat.isDirectory()) { if (blackDirs.indexOf(file) === -1) { await compressFiles(filePath, blackDirs); } else { console.log(`Skip directory: ${filePath}`); } } else if (/\.(png|jpe?g)$/i.test(filePath)) { console.log(`Compressing ${filePath}...`); const source = tinify.fromFile(filePath); await source.toFile(filePath); } } }
function task(path) { const inputDir = path.resolve(__dirname, path); const blackDirs = [] compressFiles(inputDir, blackDirs).then(() => { console.log('All files compressed successfully!'); }).catch((err) => { console.error('Error occurred while compressing files:', err); }); }
const absolutePath = "目标目录完整路径(E:/images/xxx/)"; task(absolutePath);
|