url-rewriter.js
1.3 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
52
53
var path = require('path');
module.exports = {
process: function(data, options) {
var tempData = [];
var nextStart = 0;
var nextEnd = 0;
var cursor = 0;
for (; nextEnd < data.length; ) {
nextStart = data.indexOf('url(', nextEnd);
if (nextStart == -1)
break;
nextEnd = data.indexOf(')', nextStart + 4);
if (nextEnd == -1)
break;
tempData.push(data.substring(cursor, nextStart));
var url = data.substring(nextStart + 4, nextEnd).replace(/['"]/g, '');
tempData.push('url(' + this._rebased(url, options) + ')');
cursor = nextEnd + 1;
}
return tempData.length > 0 ?
tempData.join('') + data.substring(cursor, data.length) :
data;
},
_rebased: function(url, options) {
var specialUrl = url[0] == '/' ||
url.substring(url.length - 4) == '.css' ||
url.indexOf('data:') === 0 ||
/^https?:\/\//.exec(url) !== null ||
/__\w+__/.exec(url) !== null;
var rebased;
if (specialUrl)
return url;
if (options.absolute) {
rebased = path
.resolve(path.join(options.fromBase, url))
.replace(options.toBase, '');
} else {
rebased = path.relative(options.toBase, path.join(options.fromBase, url));
}
return process.platform == 'win32' ?
rebased.replace(/\\/g, '/') :
rebased;
}
};