-
Notifications
You must be signed in to change notification settings - Fork 13
/
index.js
50 lines (43 loc) · 1.28 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
'use strict';
var gutil = require('gulp-util');
var through = require('through2');
var cheerio = require('cheerio');
var fs = require('fs');
var path = require('path');
var mime = require('mime');
module.exports = function() {
// create a stream through which each file will pass
return through.obj(function(file, enc, callback) {
if (file.isNull()) {
this.push(file);
// do nothing if no contents
return callback();
}
if (file.isStream()) {
this.emit('error', new gutil.PluginError('gulp-img64', 'Streaming not supported'));
return callback();
}
if (file.isBuffer()) {
var $ = cheerio.load(String(file.contents));
$('img').each(function() {
if (this.attr('src')) {
var ssrc = this.attr('src');
var isdata = ssrc.indexOf("data");
if (ssrc != "" && typeof ssrc != 'undefined' && isdata !== 0) {
var spath = path.join(file.base, ssrc);
var mtype = mime.lookup(spath);
if (mtype != 'application/octet-stream') {
console.log(mtype);
var sfile = fs.readFileSync(spath);
var simg64 = new Buffer(sfile).toString('base64');
this.attr('src', 'data:' + mtype + ';base64,' + simg64);
}
}
}
});
var output = $.html();
file.contents = new Buffer(output);
return callback(null, file);
}
});
};