-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathindex.js
135 lines (110 loc) · 2.87 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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
const request = require('request');
const cheerio = require('cheerio');
const async = require('async');
const url = require('url');
const ProgressBar = require('progress');
class SiteMapCrawler {
static start(links, isProgress, isLog, isCounting, callback) {
const siteMap = {};
let bar;
if (isProgress) {
bar = new ProgressBar('siteMap-crawling [:bar] :percent', {total: links.length});
}
async.each(links, (link, callback) => {
const done = () => {
if (isProgress) {
bar.tick();
}
callback();
}
request(link, (err, res, body) => {
if (err) {
if (isLog) {
const {errno, code, syscall, host} = err;
console.log(`\nError: ${errno} ${code} ${syscall}, ${host}`);
}
return done();
}
const $ = cheerio.load(body);
const hrefs = $('[href]');
let filteredLinks = new Set();
hrefs.each((i) => {
const href = this.filterLink(link, hrefs.eq(i).attr('href'));
if (href) {
filteredLinks.add(href);
}
});
filteredLinks = [...filteredLinks];
if (filteredLinks.length > 0) {
siteMap[link] = filteredLinks;
}
return done();
});
}, (err) => {
if (err) {
return callback(err);
}
const count = Object.keys(siteMap).length;
const siteMapObj = isCounting ? {count, siteMap} : siteMap[links];
callback(null, siteMapObj);
});
}
static filterLink(parent, href) {
const ignores = [
'^javascript',
'css',
'ico',
'#',
'^\/$',
'^#none$',
'^$',
'@',
'png',
'pdf$',
'^tel',
'^sms',
'^mailto',
'admin',
'login',
'register'
];
const rIgnores = new RegExp(ignores.join('|'), 'i');
if (href.startsWith('http')) {
const parentHostName = new URL(parent).hostname;
const hrefHostName = new URL(href).hostname;
if (parentHostName === hrefHostName && !(href.match(rIgnores))) {
return href;
}
}
if (!(href.match(rIgnores)) && !(href.includes('//'))) {
return url.resolve(parent, href);
}
return null;
}
}
const attachProtocol = (link) => {
if (!(link.startsWith('http'))) {
return 'http://' + link;
}
return link
}
const siteMap = (link, opts, callback) => {
let isProgress, isLog, isCounting = true;
if (typeof opts === 'function') {
callback = opts;
} else {
isProgress = opts.isProgress || false;
isLog = opts.isLog || false;
}
if (typeof link === 'string') {
link = attachProtocol(link);
link = [link];
isCounting = false;
} else {
link = link.map(l => {
return attachProtocol(l);
});
}
SiteMapCrawler.start(link, isProgress, isLog, isCounting, callback);
}
module.exports = siteMap;