8000 Add package.json and early version of index.js · D3R/gulp-css-image-hash@62a1bab · GitHub
[go: up one dir, main page]

Skip to content

Commit 62a1bab

Browse files
committed
Add package.json and early version of index.js
Currently the index.js is mostly a port of the original PHP version, only handles buffers and not streams and also can't be used recursively
0 parents  commit 62a1bab

File tree

2 files changed

+85
-0
lines changed

2 files changed

+85
-0
lines changed

index.js

Lines changed: 71 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,71 @@
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;

package.json

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
{
2+
"name": "gulp-css-image-hash",
3+
"version": "1.0.0",
4+
"description": "Append a hash of the images value to references in CSS",
5+
"main": "./index.js",
6+
"dependencies": {
7+
"async": "^0.9.0",
8+
"through2": "*"
9+
},
10+
"repository": {
11+
"type": "git",
12+
"url": "git+https://bitbucket.org/stuartloxton/gulp-css-image-hash.git"
13+
}
14+
}

0 commit comments

Comments
 (0)
0