cli.js
2.49 KB
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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
#!/usr/bin/env node
const yargsParser = require('yargs-parser')
const colors = require('colors')
const fs = require('fs')
const glob = require('glob')
const jo = require('./main.js')
const manifest = require('../package.json')
const promisify = require('util').promisify
const argv = yargsParser(process.argv.slice(2), {
boolean: ['version', 'help'],
number: ['quality', 'jpegjsMaxResolutionInMP', 'jpegjsMaxMemoryUsageInMB'],
})
if (argv.version) {
console.log(manifest.name + ' ' + manifest.version)
process.exit(0)
}
if (argv.help || argv._.length === 0) {
const help = [
'',
'Rotate JPEG images based on EXIF orientation',
'',
colors.underline('Usage'),
'jpeg-autorotate <path>',
'',
colors.underline('Options'),
'--quality=<1-100> JPEG output quality',
'--jpegjsMaxResolutionInMP=<num> jpeg-js maxResolutionInMP option',
'--jpegjsMaxMemoryUsageInMB=<num> jpeg-js maxMemoryUsageInMB option',
'--version Output current version',
'--help Output help',
'',
]
console.log(help.join('\n'))
process.exit(0)
}
listFiles()
.then(processFiles)
.then(() => {
process.exit(0)
})
function listFiles() {
return Promise.all(argv._.map((arg) => promisify(glob)(arg, {}))).then((files) => {
return [].concat.apply([], files)
})
}
function processFiles(files, index = 0) {
if (index + 1 > files.length) {
return Promise.resolve()
}
const filePath = files[index]
const options = {
quality: argv.quality,
jpegjsMaxResolutionInMP: argv.jpegjsMaxResolutionInMP,
jpegjsMaxMemoryUsageInMB: argv.jpegjsMaxMemoryUsageInMB,
}
return jo
.rotate(filePath, options)
.then(({buffer, orientation, quality, dimensions}) => {
return promisify(fs.writeFile)(files[index], buffer).then(() => {
return {orientation, quality, dimensions}
})
})
.then(({orientation, quality, dimensions}) => {
const message =
'Processed (Orientation: ' +
orientation +
') (Quality: ' +
quality +
'%) (Dimensions: ' +
dimensions.width +
'x' +
dimensions.height +
')'
console.log(filePath + ': ' + colors.green(message))
})
.catch((error) => {
const isFatal = error.code !== jo.errors.correct_orientation
console.log(filePath + ': ' + (isFatal ? colors.red(error.message) : colors.yellow(error.message)))
})
.then(() => processFiles(files, index + 1))
}