-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathindex.js
312 lines (252 loc) · 6.7 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
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
/**
* Gulp plugin to optimize images using imageoptim.
*/
var chalk = require ('chalk'),
exec = require ('child_process').exec,
fs = require ('fs'),
md5 = require ('blueimp-md5'),
path = require ('path'),
through = require ('through2')
/**
* Assert to parameter is of type object.
*
* @param {Mixed} param - The parameter to check the type of
*
* @throws {TypeError} Throws TypeError is actual type is not Object
*/
var assertObject = function (param) {
var type = ({}).toString.call (param).replace ('[object ', '').replace (']', '')
if (type !== 'Object') {
throw new TypeError('Expected object but got ' + type)
}
}
/**
* Assign all properties from a source object to a destination object.
*
* @param {Object} dest - The object to be updated
* @param {Object} src - The source object to assign missing properties from
* @return {Object} - Returns updated object
*
* @throws {TypeError} - Throws TypeError if expected parameters are not objects
*/
var assign = function (dest, src) {
assertObject (dest)
assertObject (src)
Object.keys (src).forEach (function (i) {
dest[i] = src[i]
})
return dest
}
/**
* Create and return a new object with all the properties of the provided object.
*
* @param {Object} obj - The object to clone
* @return {Object} - Returns clone of provided object
*
* @throws {TypeError} - Throws TypeError if expected parameter is not an object
*/
var clone = function (obj) {
assertObject (obj)
var newObj = {}
Object.keys (obj).forEach (function (i) {
newObj[i] = obj[i]
});
return newObj
}
/**
* Plugin.
*/
function BatchOptimizer () {
/**
* Default configuration options.
* @type {Object}
*/
var config = {}
/**
* Whether to display optimization status or not.
* @type {Boolean}
*/
config.status = true
/**
* Batch size is the number of files to batch optimize.
* @type {Int}
*/
config.batchSize = 400
/**
* Whether to use jpegmini or not.
* @type {Boolean}
*
* Before enabling this feature complete the following steps
* 1. Install JPEGmini
* 2. Open JPEGmini then add Terminal.app (or iTerm.app) to 'support for assistive devices' whitelist
*/
config.jpegmini = false
/**
* Array of files to batch optimize.
* @type {Array}
*/
var batchFiles = []
/**
* Reference to stream.
* @type {Object}
*/
var stream = null
/**
* Remove directory.
*
* @param {String} dirPath - Path to directory
*/
var removeDirectory = function (dirPath) {
var files = []
if (fs.lstatSync (dirPath).isDirectory ()) {
files = fs.readdirSync (dirPath)
files.forEach (function (file) {
var curPath = path.join (dirPath, file)
if (fs.lstatSync (curPath).isDirectory ()) {
removeDirectory (curPath)
} else {
fs.unlinkSync (curPath)
}
})
fs.rmdirSync (dirPath)
}
}
/**
* Batch optimize files and push.
*
* @param {Array} files - Array of files to batch optimize
* @param {Object} options - Options. Currently status is supported as boolean indicating whether to display optmization result status or not
* @param {Function} next - The callback to continue processing
*/
var batchOptimize = function (files, options, next) {
if (files.length === 0)
next (files)
var batchDir = md5 (Date.now ()),
jpegminiEnabled = options.jpegmini ? '--jpegmini' : '',
scriptParams = path.normalize (batchDir) + ' ' + jpegminiEnabled
// Make batch directory
fs.mkdirSync (batchDir)
// Add files to optimize to batch directory
for (var i = 0, length = files.length; i < length; i++) {
var file = files[i]
file.batchFilePath = path.join (batchDir, md5 (file.path) + path.extname (file.path))
fs.writeFileSync (file.batchFilePath, file.contents)
}
// Optimize files
exec ('bash node_modules/gulp-imageoptim/scripts/optimize.bash ' + scriptParams, function (error, stdout) {
var result = {}
if (error === null) {
var savings = parseInt (stdout.replace (/.*\(([0-9]+)(\.[0-9]+)?\%\)/, '$1')),
msg = ''
if (savings > 0) {
// Copy optimized file contents to original and remove file
for (var i = 0, length = files.length; i < length; i++) {
var file = files[i]
file.contents = new Buffer(fs.readFileSync (file.batchFilePath))
stdout = stdout.replace (file.batchFilePath, path.basename (file.path))
}
msg = stdout.replace ('TOTAL was', 'Filesize total was')
} else {
msg = 'Saving: 0%\n'
}
result = {
'files' : files.length,
'msg' : msg,
'savings' : savings,
'type' : 'success'
}
} else {
console.error (error)
}
// Delete batch directory
removeDirectory (batchDir)
// Display optmization result status?
if (options.status) {
displayOptimizationResults (result)
}
next (files)
})
}
/**
* Push files to stream.
*
* @param {Array} files - Array of optimized files to push
*/
var pushFiles = function (files) {
if (typeof stream !== 'object')
return
for (var i = 0, length = files.length; i < length; i++) {
stream.push (files[i])
}
}
/**
* Display batch results.
*
* @param {Object} result - The result to display from batch optimization
*/
var displayOptimizationResults = function (result) {
if (typeof result === 'object') {
switch (result.type) {
case 'success':
console.log ('Batch of ' + result.files + ' files optimized:\n' + chalk.gray (result.msg))
break
case 'error':
console.log (chalk.red (result.msg))
break
}
}
}
/**
* Public functions
*/
return {
/**
* Optimize images.
*
* @param {Object} opts - Options to customize optimization
* @return {Stream} - Returns through object
*/
'optimize' : function (opts) {
var options = clone (config)
opts = opts || {};
// Set config optiosn to use for this current optimization session
assign (options, opts)
if (options.status) {
console.log (chalk.yellow.bgBlack ('Starting image optimization ... this may take a while.'))
}
return through.obj (function (file, enc, cb) {
stream = this
// If file is null continue
if (file.isNull ()) {
cb (null, file)
return
}
// Add file to batch
batchFiles.push (file)
if (batchFiles.length >= options.batchSize) {
batchOptimize (batchFiles, options, function (files) {
pushFiles (files)
batchFiles = []
cb ()
})
} else {
cb ()
}
},
function (cb) {
batchOptimize (batchFiles, options, function (files) {
pushFiles (files)
batchFiles = []
if (options.status) {
console.log (chalk.green.bgBlack ('Optimization complete!'))
}
cb ()
})
})
}
}
}
/**
* Export
*/
module.exports = BatchOptimizer ()