const {init, extnameCheck, runExtnames} = require('./minify') const path = require('path') const fs = require('fs') const analysisUrl = url => { if (!url){ throw '无效路径' } else if (path.isAbsolute(url)) { return url } else { return path.join(__dirname, url) } } const analysisArgs = args => { const config = { input: analysisUrl(args.shift()), width: 0, height: 0, quality: 75, format: undefined } if (args.length >= 5 || ( args.length && isNaN(Number(args[args.length - 1])) && !extnameCheck(args[args.length - 1])) ) { config.output = analysisUrl(args.pop()) } else { config.output = config.input } switch(args.length) { case 0: break; case 1: if (extnameCheck(args[0])) { config.format = args[0] } else { config.quality = args[0] } break; case 2: if (extnameCheck(args[1])) { config.format = args[1] config.quality = args[0] } else { config.width = args[0] config.height = args[1] } break; case 4: config.format = extnameCheck(args[3]) && args[3] default: if (extnameCheck(args[2])) { config.format = args[2] config.width = args[0] config.height = args[1] } else { config.quality = args[0] config.width = args[1] config.height = args[2] } } if (config.format) { let extIndex = config.output.lastIndexOf('.') let extNameLen = config.output.length - extIndex - 1 let maxLen = Math.max(runExtnames.map(s => s.length)) if (!~extIndex || extNameLen > maxLen) { config.output += '.' + config.format } else { config.output = config.output.substring(0, extIndex) + '.' + config.format } } return config } const main = async () => { const config = analysisArgs(process.argv.slice(2)) if (!fs.existsSync(config.input)) { throw config.input + ' No such file or directory' } const gm = await init({fileUri: config.input}) if (config.width && config.height) { gm.zoom({width: config.width, height: config.height}) } if (config.quality) { gm.quality(config.quality) } gm.write(config.output, err => { if (err) { console.error(err) } else { console.log('成功转换,存储路径为', config.output) } }) } main();