-
Notifications
You must be signed in to change notification settings - Fork 8
/
index.js
60 lines (49 loc) · 1.85 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
51
52
53
54
55
56
57
58
59
60
var vinylFs = require('vinyl-fs');
var cheerio = require('cheerio');
var through = require('through2');
var vinylFile = require('vinyl-file');
var async = require('async');
var extend = require('extend');
var fs = require('fs');
var path = require('path');
module.exports = domSrc;
function domSrc(config){
var html = fs.readFileSync(path.join(process.cwd(),config.file),'utf8');
var files = findFilenames(html, config);
return vinylFs.src(files,config.options || {});
}
function findFilenames(html, config) {
var $ = cheerio.load(html);
return $(config.selector).map(function(i,elem){
return $(elem).attr(config.attribute);
}).toArray().filter(function(item){
return (item !== undefined && item.substring(0,4) !== 'http' && item.substring(0,2) !== '//');
}).map(function(item){
var cwd = config.cwd ? config.cwd : path.dirname(config.file);
return path.join(cwd,item);
});
}
domSrc.duplex = function(config) {
return through.obj(findAndReadFiles);
function findAndReadFiles(htmlFile, encoding, throughCallback) {
// copy config and set config.file to current html file
// so cwd is resolved correctly when scanning html for filenames
var configCopy = extend({}, config);
configCopy.file = htmlFile.path;
var html = htmlFile.contents.toString();
var filenames = findFilenames(html, configCopy);
if (filenames.length == 0) {
return throughCallback();
}
var throughStream = this;
async.eachSeries(filenames, function(filename, eachCallback) {
vinylFile.read(filename, function(err, file) {
if (err) return eachCallback(err);
throughStream.push(file);
eachCallback();
});
}, function(err) {
throughCallback(err);
});
}
};