-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
105 lines (95 loc) · 3.15 KB
/
index.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
'use strict';
const fs = require('fs');
const path = require('path');
const crypto = require('crypto');
const mkdirp = require('mkdirp');
const tinify = require('tinify');
const loaderUtils = require('loader-utils');
module.exports = function(content) {
const callback = this.async();
const options = loaderUtils.getOptions(this);
let hashName, filePath;
content = fs.readFileSync(this.resourcePath);
if (options.cachePath) {
hashName = crypto.createHash('md5').update(content).digest("hex");
filePath = path.join(options.cachePath, `${hashName}.png`);
if (fs.existsSync(filePath)) {
console.log(filePath, ' cache hit');
fs.readFile(filePath, (err, data) => {
if (err) {
return callback(err);
}
callback(null, data);
})
return;
}
}
this.cacheable && this.cacheable();
const selectedKeys = [];
const { keys, proxy } = options;
if (!keys || !Array.isArray(keys) || keys.length == 0) {
callback(new Error('tinypng need key'));
return;
}
if (proxy) {
tinify.proxy = proxy;
}
if (typeof keys == 'string') {
tinify.key = keys;
selectedKeys.push(keys);
} else {
let key = keys[parseInt(Math.random() * keys.length)];
selectedKeys.push(key);
tinify.key = key;
}
let resPath = this.resourcePath;
console.log('before', this.resourcePath, content.length);
let timeout = false,
timer = null;
function requestCompress() {
tinify.fromBuffer(content).toBuffer(function(err, resultData) {
if (timeout) {
return;
}
clearTimeout(timer);
if (err && err.status >= 400 && err.status < 500) {
if (selectedKeys.length == keys.length) {
return callback(null, content);
}
do {
let key = keys[parseInt(Math.random() * keys.length)];
} while (selectedKeys.indexOf(key) == -1)
selectedKeys.push(key);
tinify.key = key;
requestCompress();
}
if (err) return callback(null, content);
console.log('after', resPath, resultData.length)
if (options.cachePath) {
mkdirp(options.cachePath, (err) => {
console.log('mkdir err', err);
if (err) {
return callback(null, resultData);
}
fs.writeFile(filePath, resultData, () => {
callback(null, resultData);
});
})
} else {
callback(null, resultData);
}
});
}
requestCompress();
timer = setTimeout(() => {
console.log(resPath, ' timeout');
timeout = true;
callback(null, content);
}, 6000);
}
module.exports.pitch = function(remainingRequest) {
let isPng = /\.png$/.test(this.resourcePath);
if (!isPng) {
return fs.readFileSync(this.resourcePath);
}
}