-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathgzip-compress.js
80 lines (69 loc) · 2.46 KB
/
gzip-compress.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
import * as fs from "fs";
import * as util from "util";
import {zopfliAdapter} from "./zopfli-adapter.js";
const readFile = util.promisify(fs.readFile);
const writeFile = util.promisify(fs.writeFile);
async function zopfliCompressFile(file, options) {
const stat = fs.statSync(file);
const content = await readFile(file);
let compressed1 = null;
let compressed2 = null;
if (options.zopfliBlocksplittinglast === 'true') {
compressed2 = await zopfliPromisify(content, {
numiterations: options.numiterations,
blocksplitting: true,
blocksplittinglast: true,
blocksplittingmax: 15
});
} else if (options.zopfliBlocksplittinglast === 'both') {
compressed1 = await zopfliPromisify(content, {
numiterations: options.numiterations,
blocksplitting: true,
blocksplittinglast: false,
blocksplittingmax: 15
});
compressed2 = await zopfliPromisify(content, {
numiterations: options.numiterations,
blocksplitting: true,
blocksplittinglast: true,
blocksplittingmax: 15
});
} else {
compressed1 = await zopfliPromisify(content, {
numiterations: options.numiterations,
blocksplitting: true,
blocksplittinglast: false,
blocksplittingmax: 15
});
}
if (compressed1 !== null && compressed1.length < stat.size) {
if (compressed2 !== null && compressed2.length < compressed1.length) {
await writeFile(file + '.gz', compressed2);
return compressed2.length;
} else {
await writeFile(file + '.gz', compressed1);
return compressed1.length;
}
} else if (compressed2 !== null && compressed2.length < stat.size) {
await writeFile(file + '.gz', compressed2);
return compressed2.length;
}
return stat.size;
}
async function zopfliPromisify(content, options) {
const zopfli = await zopfliAdapter();
return new Promise((resolve, reject) => {
zopfli.gzip(content, options, (err, compressedContent) => {
if (!err) {
resolve(compressedContent);
} else {
reject(err);
}
});
});
}
process.on('message', async (message) => {
const fileSize = await zopfliCompressFile(message.name, message.options);
process.send(fileSize);
});
process.send({ready: true});