forked from wpfpizicai/gulp-md5-plus
-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathindex.js
57 lines (47 loc) · 1.68 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
var path = require('path')
, gutil = require('gulp-util')
, through = require('through2')
, crypto = require('crypto')
, fs = require('fs')
, glob = require('glob')
, escapeRegExp = require('escape-string-regexp');
module.exports = function (size, ifile) {
size = size | 0;
return through.obj(function (file, enc, cb) {
if (file.isStream()) {
this.emit('error', new gutil.PluginError('gulp-debug', 'Streaming not supported'));
return cb();
}
if(!file.contents){
return cb();
}
var d = calcMd5(file, size)
, filename = path.basename(file.path)
, relativepath = path.relative(file.base ,file.path)
, sub_namepath = relativepath.replace(new RegExp(escapeRegExp(filename)) , "").split(path.sep).join('/')
, dir;
if(file.path[0] == '.'){
dir = path.join(file.base, file.path);
} else {
dir = file.path;
}
dir = path.dirname(dir);
var md5_filename = filename + '?' + d;
ifile && glob(ifile,function(err, files){
if(err) return console.log(err);
files.forEach(function(ilist){
var result = fs.readFileSync(ilist,'utf8').replace(new RegExp(sub_namepath + filename + "[0123456789abcdef?]*", "g"), sub_namepath + md5_filename);
fs.writeFileSync(ilist, result, 'utf8');
})
})
this.push(file);
cb();
}, function (cb) {
cb();
});
};
function calcMd5(file, slice){
var md5 = crypto.createHash('md5');
md5.update(file.contents, 'utf8');
return slice >0 ? md5.digest('hex').slice(0, slice) : md5.digest('hex');
}