1 | #!/usr/bin/env node
|
2 | 'use strict'
|
3 |
|
4 | const colors = require('colors')
|
5 | const argv = require('yargs').argv
|
6 | const async = require('async')
|
7 | const fs = require('fs')
|
8 | const glob = require('glob')
|
9 |
|
10 | const jo = require('./main.js')
|
11 | const manifest = require('../package.json')
|
12 |
|
13 | if (argv.version) {
|
14 | console.log(manifest.name + ' ' + manifest.version)
|
15 | process.exit(0)
|
16 | }
|
17 |
|
18 | if (argv.help || typeof argv._ === 'undefined' || argv._.length === 0) {
|
19 | const help = [
|
20 | '',
|
21 | 'Rotates JPEG images based on EXIF orientation',
|
22 | '',
|
23 | colors.underline('Usage'),
|
24 | 'jpeg-autorotate <path>',
|
25 | '',
|
26 | colors.underline('Options'),
|
27 | '--quality=<0-100> JPEG output quality',
|
28 | '--jobs=<number> How many concurrent jobs to run (default is 10)',
|
29 | '--version Outputs current version',
|
30 | '--help Outputs help',
|
31 | '',
|
32 | ]
|
33 | console.log(help.join('\n'))
|
34 | process.exit(0)
|
35 | }
|
36 |
|
37 | const jobs =
|
38 | typeof argv.jobs !== 'undefined' && argv.jobs.toString().search(/^[0-9]+$/) === 0 ? parseInt(argv.jobs) : 10
|
39 | const quality =
|
40 | typeof argv.quality !== 'undefined' && argv.quality.toString().search(/^[0-9]+$/) === 0 ? parseInt(argv.quality) : 100
|
41 |
|
42 | const queue = async.queue(_processFile, jobs)
|
43 | queue.drain = _onAllFilesProcessed
|
44 | argv._.map(function(path) {
|
45 | glob(path, {}, function(error, files) {
|
46 | if (error) {
|
47 | _onFileProcessed(error, path, null)
|
48 | return
|
49 | }
|
50 | files.map(function(file) {
|
51 | queue.push({path: file}, _onFileProcessed)
|
52 | })
|
53 | })
|
54 | })
|
55 |
|
56 |
|
57 |
|
58 |
|
59 |
|
60 |
|
61 | function _processFile(task, callback) {
|
62 | jo.rotate(task.path, {quality: quality}, function(error, buffer, orientation) {
|
63 | if (error) {
|
64 | callback(error, task.path, orientation)
|
65 | return
|
66 | }
|
67 | fs.writeFile(task.path, buffer, function(error) {
|
68 | callback(error, task.path, orientation)
|
69 | })
|
70 | })
|
71 | }
|
72 |
|
73 |
|
74 |
|
75 |
|
76 |
|
77 |
|
78 |
|
79 | function _onFileProcessed(error, path, orientation) {
|
80 | if (error) {
|
81 | console.log(
|
82 | path +
|
83 | ': ' +
|
84 | (error.code === jo.errors.correct_orientation ? colors.yellow(error.message) : colors.red(error.message))
|
85 | )
|
86 | } else {
|
87 | console.log(path + ': ' + colors.green('Processed (Orientation was ' + orientation + ')'))
|
88 | }
|
89 | }
|
90 |
|
91 |
|
92 |
|
93 |
|
94 | function _onAllFilesProcessed() {
|
95 | process.exit(0)
|
96 | }
|