UNPKG

2.62 kBJavaScriptView Raw
1#!/usr/bin/env node
2
3const yargsParser = require('yargs-parser')
4const colors = require('colors')
5const fs = require('fs')
6const glob = require('glob')
7const jo = require('./main.js')
8const manifest = require('../package.json')
9const promisify = require('util').promisify
10
11const argv = yargsParser(process.argv.slice(2), {
12 boolean: ['version', 'help'],
13 number: ['quality', 'jpegjsMaxResolutionInMP', 'jpegjsMaxMemoryUsageInMB'],
14})
15
16if (argv.version) {
17 console.log(manifest.name + ' ' + manifest.version)
18 process.exit(0)
19}
20
21if (argv.help || argv._.length === 0) {
22 const help = [
23 '',
24 'Rotate JPEG images based on EXIF orientation',
25 '',
26 colors.underline('Usage'),
27 'jpeg-autorotate <path>',
28 '',
29 colors.underline('Options'),
30 '--quality=<1-100> JPEG output quality',
31 '--jpegjsMaxResolutionInMP=<num> jpeg-js maxResolutionInMP option',
32 '--jpegjsMaxMemoryUsageInMB=<num> jpeg-js maxMemoryUsageInMB option',
33 '--version Output current version',
34 '--help Output help',
35 '',
36 ]
37 console.log(help.join('\n'))
38 process.exit(0)
39}
40
41listFiles()
42 .then(processFiles)
43 .then(() => {
44 process.exit(0)
45 })
46 .catch((error) => {
47 console.log(error.message)
48 process.exit(1)
49 })
50
51function listFiles() {
52 return Promise.all(argv._.map((arg) => promisify(glob)(arg, {}))).then((files) => {
53 return [].concat.apply([], files)
54 })
55}
56
57function processFiles(files, index = 0) {
58 if (index + 1 > files.length) {
59 return Promise.resolve()
60 }
61 const filePath = files[index]
62 const options = {
63 quality: argv.quality,
64 jpegjsMaxResolutionInMP: argv.jpegjsMaxResolutionInMP,
65 jpegjsMaxMemoryUsageInMB: argv.jpegjsMaxMemoryUsageInMB,
66 }
67 return jo
68 .rotate(filePath, options)
69 .then(({buffer, orientation, quality, dimensions}) => {
70 return promisify(fs.writeFile)(files[index], buffer).then(() => {
71 return {orientation, quality, dimensions}
72 })
73 })
74 .then(({orientation, quality, dimensions}) => {
75 const message =
76 'Processed (Orientation: ' +
77 orientation +
78 ') (Quality: ' +
79 quality +
80 '%) (Dimensions: ' +
81 dimensions.width +
82 'x' +
83 dimensions.height +
84 ')'
85 console.log(filePath + ': ' + colors.green(message))
86 })
87 .catch((error) => {
88 const isFatal = error.code !== jo.errors.correct_orientation
89 console.log(filePath + ': ' + (isFatal ? colors.red(error.message) : colors.yellow(error.message)))
90 })
91 .then(() => processFiles(files, index + 1))
92}