main.js 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106
  1. const {init, extnameCheck, runExtnames} = require('./minify')
  2. const path = require('path')
  3. const fs = require('fs')
  4. const analysisUrl = url => {
  5. if (!url){
  6. throw '无效路径'
  7. } else if (path.isAbsolute(url)) {
  8. return url
  9. } else {
  10. return path.join(__dirname, url)
  11. }
  12. }
  13. const analysisArgs = args => {
  14. const config = {
  15. input: analysisUrl(args.shift()),
  16. width: 0,
  17. height: 0,
  18. quality: 75,
  19. format: undefined
  20. }
  21. if (args.length >= 5 || (
  22. args.length &&
  23. isNaN(Number(args[args.length - 1])) &&
  24. !extnameCheck(args[args.length - 1]))
  25. ) {
  26. config.output = analysisUrl(args.pop())
  27. } else {
  28. config.output = config.input
  29. }
  30. switch(args.length) {
  31. case 0:
  32. break;
  33. case 1:
  34. if (extnameCheck(args[0])) {
  35. config.format = args[0]
  36. } else {
  37. config.quality = args[0]
  38. }
  39. break;
  40. case 2:
  41. if (extnameCheck(args[1])) {
  42. config.format = args[1]
  43. config.quality = args[0]
  44. } else {
  45. config.width = args[0]
  46. config.height = args[1]
  47. }
  48. break;
  49. case 4:
  50. config.format = extnameCheck(args[3]) && args[3]
  51. default:
  52. if (extnameCheck(args[2])) {
  53. config.format = args[2]
  54. config.width = args[0]
  55. config.height = args[1]
  56. } else {
  57. config.quality = args[0]
  58. config.width = args[1]
  59. config.height = args[2]
  60. }
  61. }
  62. if (config.format) {
  63. let extIndex = config.output.lastIndexOf('.')
  64. let extNameLen = config.output.length - extIndex - 1
  65. let maxLen = Math.max(runExtnames.map(s => s.length))
  66. if (!~extIndex || extNameLen > maxLen) {
  67. config.output += '.' + config.format
  68. } else {
  69. config.output = config.output.substring(0, extIndex) + '.' + config.format
  70. }
  71. }
  72. return config
  73. }
  74. const main = async () => {
  75. const config = analysisArgs(process.argv.slice(2))
  76. if (!fs.existsSync(config.input)) {
  77. throw config.input + ' No such file or directory'
  78. }
  79. const gm = await init({fileUri: config.input})
  80. if (config.width && config.height) {
  81. gm.zoom({width: config.width, height: config.height})
  82. }
  83. if (config.quality) {
  84. gm.quality(config.quality)
  85. }
  86. gm.write(config.output, err => {
  87. if (err) {
  88. console.error(err)
  89. } else {
  90. console.log('成功转换,存储路径为', config.output)
  91. }
  92. })
  93. }
  94. main();