123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106 |
- 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();
|