UNPKG

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