This repository has been archived by the owner on Sep 4, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathindex.js
102 lines (88 loc) · 2.82 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
/*jshint bitwise:true, camelcase:true, curly:true, eqeqeq:true, forin:true, immed:true, latedef:true,
newcap:true, noarg:true, noempty:true, nonew:true, plusplus:true, regexp:true, undef:true,
unused:true, strict:true, trailing:true, indent:2, quotmark:single, esnext:true, node:true */
var es = require('event-stream');
var clone = require('clone');
var zopfli = require('node-zopfli');
const PLUGIN_NAME = 'gulp-zopfli';
/**
*
* @param {Object} opts
* @param {String} opts.format gzip || deflate || zlib
* @param {Number} opts.thresholdRatio if compression ratio does not reach the threshold,
* does not compress, default to 0
* @param {String} opts.thresholdBehavior if compression ratio does not reach the threshold,
* "original" to output original file, or
* "blank" (default) to output nothing
* @returns {Stream}
*/
module.exports = function(opts) {
'use strict';
// default options
var options = opts || {};
var format = options.format || 'gzip';
var ext;
if(format === 'gzip') {
ext = '.gz';
} else if(format === 'deflate') {
ext = '.deflate';
} else if(format === 'zlib') {
ext = '.zz';
}
// delete format option
if(options.format !== null) {
delete options.format;
}
var compress = function(file, callback) {
// pass along empty files
if(file.isNull()) {
return callback(null, file);
}
// clone file and append the extension
var newFile = clone(file);
newFile.path += ext;
newFile.shortened += ext;
// Check if file is a buffer or a stream
if(file.isBuffer()) {
// File contents is a buffer
var zcb = function(err, buffer) {
if(!err) {
if(options.thresholdRatio > file.contents.length / buffer.length) {
if(options.thresholdBehavior === 'original'){
// output original file
return callback(null, file);
}
// output nothing
return callback();
}
newFile.contents = buffer;
// output compressed file
return callback(null, newFile);
}
callback(err, null);
};
if(format === 'gzip') {
zopfli.gzip(file.contents, options, zcb);
} else if(format === 'deflate') {
zopfli.deflate(file.contents, options, zcb);
} else if(format === 'zlib') {
zopfli.zlib(file.contents, options, zcb);
}
} else if(file.isStream()) {
// File contains a stream
var z;
if(format === 'gzip') {
z = zopfli.createGzip(options);
} else if(format === 'deflate') {
z = zopfli.createDeflate(options);
} else if(format === 'zlib') {
z = zopfli.createZlib(options);
}
newFile.contents = file.contents
.pipe(z);
// .pipe(es.through());
callback(null, newFile);
}
};
return es.map(compress);
};