|
| 1 | +'use strict'; |
| 2 | + |
| 3 | +var through = require('through2'), |
| 4 | + async = require('async'), |
| 5 | + fs = require('fs'), |
| 6 | + crypto = require('crypto'); |
| 7 | + |
| 8 | +var PLUGIN_NAME = 'gulp-css-image-hash'; |
| 9 | + |
| 10 | +function cssImageHash(webPath) { |
| 11 | + var stream = through.obj(function(file, enc, cb) { |
| 12 | + var that = this; |
| 13 | + |
| 14 | + var regex = /url\(([^\)]+)\)/g, |
| 15 | + matches = null; |
| 16 | + |
| 17 | + var asString = ''; |
| 18 | + |
| 19 | + if (file.isBuffer()) { |
| 20 | + asString = String(file.contents); |
| 21 | + |
| 22 | + matches = asString.match(regex); |
| 23 | + } |
| 24 | + |
| 25 | + if (file.isStream()) { |
| 26 | + this.emit('error', new PluginError(PLUGIN_NAME, 'Streams are not supported!')); |
| 27 | + return cb(); |
| 28 | + } |
| 29 | + |
| 30 | + if (matches != null && matches.length) { |
| 31 | + var pairs = []; |
| 32 | + matches = matches.forEach(function(curValue) { |
| 33 | + // remove url() |
| 34 | + var path = curValue.slice(4).slice(0, -1); |
| 35 | + |
| 36 | + // Remove surrounding quotes |
| 37 | + if (path[0] == '"' || path[0] == "'") { |
| 38 | + path = path.slice(1).slice(0, -1); |
| 39 | + } |
| 40 | + |
| 41 | + pairs.push([curValue, path]); |
| 42 | + }); |
| 43 | + |
| 44 | + async.eachSeries(pairs, function(tuple, callback) { |
| 45 | + |
| 46 | + var md5 = crypto.createHash('md5'), |
| 47 | + file = fs.ReadStream(webPath + tuple[1]), |
| 48 | + hash = ''; |
| 49 | + |
| 50 | + file.on('data', function(d) { |
| 51 | + md5.update(d); |
| 52 | + }); |
| 53 | + file.on('end', function() { |
| 54 | + hash = md5.digest('hex'); |
| 55 | + asString = asString.replace(tuple[0], 'url(' + tuple[1] + '?h=' + hash + ')'); |
| 56 | + callback(); |
| 57 | + }); |
| 58 | + }, function (err) { |
| 59 | + file.contents = new Buffer(asString); |
| 60 | + that.push(file); |
| 61 | + cb(); |
| 62 | + }); |
| 63 | + } else { |
| 64 | + this.push(file); |
| 65 | + cb(); |
| 66 | + } |
| 67 | + }); |
| 68 | + return stream; |
| 69 | +}; |
| 70 | + |
| 71 | +module.exports = cssImageHash; |
0 commit comments