UNPKG

gulp-md5-assets

Version:

md5 the static file and change the names in the quoted html, forked from gulp-md5-plus

58 lines (47 loc) 1.72 kB
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'); }