-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.online.js
114 lines (105 loc) · 2.63 KB
/
index.online.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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
const tinify = require('tinify')
const fs = require('fs')
const chalk = require('chalk')
const path = require('path')
const API_KEY = "fvDPnGNpDZRJsrtR5KdM4Qcbp8RvcYhN"
tinify.key = API_KEY
let arg = process.argv[2]
const targetOnline = path.resolve("targetOnline")
const progress = require('./utils/progress')
function getName(address) {
let addressArr = address.split('/')
let name = addressArr[addressArr.length - 1]
return `${name.split(".")[0]}.min.${name.split(".")[1]}`
}
function regImg() {
// Verify the url
let reg = /^(http|https):\/\//gi;
if (!reg.test(arg)) {
console.log(chalk.bgYellow('WARN'), "Sorry, online pictures only!");
return false
}
return true
}
const MAXLEN = 7
function rebuildTarget() {
fs.readdir(targetOnline, "", (err, files) => {
if (err) throw err;
if (regImg()) {
tinify.fromUrl(arg).toFile(`${targetOnline}/${getName(arg)}`, () => {
progress.isDone = true;
console.log(
chalk.bgGreen.black("DONE"),
`The file is saved in the ${chalk.bold.underline('targetOnline')} folder`
);
});
} else {
progress.isDone = true;
}
});
}
function validityApi() {
// Validation of API key failed.
return new Promise((resolve, reject) => {
tinify.validate(function (err) {
if (err) {
reject(err)
return
}
resolve()
});
})
}
function initProgress(m) {
// init progressing..
console.log('===================================\n')
console.log('Thank you for using minify-your-img\n')
console
.log(chalk.green(
` _ _
${chalk.white('(o)--(o)')}
/${chalk.white('.______.')}\\
\\________/
./ \\.
( . , )
\ \_\\\\ //_/ /
~~ ~~ ~~`))
console.log('===================================\n')
console.log(chalk.bgBlue.black("INFO"), 'Start compressing...')
let timer = setInterval(function () {
if (progress.isDone) {
clearInterval(timer)
return
}
progress.init()
}, 1000)
}
function compresePic() {
// comprese image..
try {
fs.access(targetOnline, fs.constants.F_OK, err => {
// if there's not a targetOline dir, make it first.
if (err) {
fs.mkdir(targetOnline, () => {
rebuildTarget()
})
} else {
rebuildTarget()
}
});
} catch (error) {
throw error
}
}
function urlMin() {
initProgress(MAXLEN)
validityApi()
.then(() => {
compresePic();
})
.catch(err => {
progress.isDone = true
console.log(chalk.bgRed(`ERROR`), chalk.red(err.message))
})
}
urlMin()