forked from bbottema/gulp-js-base64-inject
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
51 lines (44 loc) · 1.68 KB
/
index.js
File metadata and controls
51 lines (44 loc) · 1.68 KB
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
var fs = require('fs');
var path = require('path');
var through = require('through2');
var xtend = require('xtend');
var mime = require('mime');
module.exports = function(options) {
var opts = xtend({
basepath: '',
pattern: /'@@import ([a-zA-Z0-9\-_.\\/]+)'/g,
debug: false
}, options);
opts.debug && console.log('Injecting resources:');
return through.obj(
function(file, enc, callback) {
if (file.isNull()) callback(null, file);
var process = function(contents) {
return contents.replace(opts.pattern, function(match, filepath) {
var fp = path.join(opts.basepath, filepath);
try {
var filecontents = mime.lookup(filepath) + ';base64,' + fs.readFileSync(filepath).toString('base64');
opts.debug && console.log(' ', filepath, 'OK');
return "'" + filecontents + "'";
}
catch (e) {
console.error('unable to read utf8 file', fp);
return "''";
}
});
};
opts.debug && console.log(' ', file.path);
if (file.isBuffer()) {
file.contents = new Buffer(process(String(file.contents)));
callback(null, file);
} else if (file.isStream()) {
file.contents.on('data', function(data) {
file.contents = new Buffer(process(data));
callback(null, file);
});
} else {
callback(null, file);
}
}
);
};