-
Notifications
You must be signed in to change notification settings - Fork 0
/
imageCompressor.js
82 lines (81 loc) · 2.7 KB
/
imageCompressor.js
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
const fs = require('fs')
const sharp = require('sharp')
const cliProgress = require('cli-progress')
const yargs = require('yargs')(process.argv.slice(2))
.option({
folder: {
alias: 'f',
describe: 'Path to the folder',
demandOption: true,
type: 'string'
},
path: {
alias: 'p',
describe: 'Path of the outputed files. Defaults to a subdirectory inside the current folder',
type: 'string',
},
output: {
alias: 'o',
describe: 'Type of the file output',
type: 'string',
default: 'jpeg',
choices: ['jpeg', 'webp', 'png']
},
quality: {
alias: 'q',
describe: 'Quality of the converted pictures',
type: 'number',
default: 70
}
})
.argv
fs.readdir(yargs.folder, (err, files) => {
if (err) {
console.log(err)
return
}
})
let destinationPath = (typeof yargs.path === 'undefined') ? yargs.folder + '/compressed' : yargs.path
fs.mkdir(destinationPath, { recursive: true }, (err) => {
fs.readdir(yargs.folder, (err, files) => {
if (err) {
console.log(err)
return
}
console.log('Starting compression for ' + files.length + ' files')
console.log('Output type: ' + yargs.output)
console.log('Quality: ' + yargs.quality)
console.log('Output folder: ' + destinationPath)
const bar = new cliProgress.SingleBar({}, cliProgress.Presets.shades_classic)
bar.start(files.length, 1)
files.forEach(file => {
if (fs.lstatSync(`${yargs.folder}/${file}`).isFile()) {
const options = {quality: yargs.quality}
let sharpObj = sharp(`${yargs.folder}/${file}`).withMetadata()
let extension
switch (yargs.output) {
case 'jpeg':
sharpObj.jpeg(options)
extension = 'jpg'
break
case 'webp':
sharpObj.webp(options)
extension = 'webp'
break
case 'png':
sharpObj.png(options)
extension = 'png'
break
}
sharpObj
.toFile(`${destinationPath}/${file.split('.')[0]}.${extension}`, (err, info) => {
if (err) {
console.log(err)
return
}
bar.increment()
})
}
})
})
})