-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcrawl.js
96 lines (79 loc) · 2.77 KB
/
crawl.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
import {URL} from 'url';
import {JSDOM} from "jsdom";
function normalizeURL(inputURL) {
const sourceURL = new URL(inputURL);
//console.log(sourceURL.hostname + stripTrailingSlash(sourceURL.pathname));
return sourceURL.hostname + stripTrailingSlash(sourceURL.pathname);
}
export { normalizeURL };
function stripTrailingSlash(input) {
return input.endsWith('/') ? input.slice(0, -1) : input;
}
function getURLsFromHTML(htmlBody, baseURL) {
const dom = new JSDOM(htmlBody);
const result = dom.window.document.querySelectorAll("a");
let resultArray = [];
for (const anchor of result){
if (anchor.hasAttribute('href')) {
let href = anchor.getAttribute("href");
try {
//convert relative URLs to absolute URLs
href = new URL(href, baseURL).href;
resultArray.push(href);
} catch (err){
console.log(`${err.message}: ${href}`)
}
}
}
return resultArray;
}
export { getURLsFromHTML }
async function crawlPage(baseURL, currentURL=baseURL, pages = {} ){
console.log(`Crawling: ${currentURL}`);
//make sure it's the same domain...
const testURL = new URL(currentURL);
if(testURL.hostname !== new URL(baseURL).hostname){
console.log(`Returning: Current URL not in base domain!: ${currentURL}`);
return pages;
}
let normalizedCurrentURL = normalizeURL(currentURL);
if(normalizedCurrentURL in pages){
pages[normalizedCurrentURL] ++;
console.log(`Returning: Link already visited: ${currentURL}}`)
return pages;
}else {
pages[normalizedCurrentURL] = 1;
}
let newURLs = await getURLsFromURL(currentURL, baseURL);
if (!Array.isArray(newURLs) || newURLs.length === 0){
console.log(`Returning: No new URLs found at: ${currentURL}`);
return pages;
}
//recursively call crawlPage with URL list
for(const newURL of newURLs){
//console.log('CurrentURL: ' +currentURL + 'newURL: ' +newURL);
pages = await crawlPage(baseURL, newURL, pages);
}
//console.log(pages);
return pages;
}
export {crawlPage};
async function getURLsFromURL(currentURL, baseURL){
let response
try{
response = await fetch(currentURL);
} catch(err){
throw new Error('Got network error: ${err.message}');
}
if(response.status > 399){
console.log(`HTTP Error: ${response.status}${response.statusText}`);
return;
}
const contentType = response.headers.get('content-type');
if(!contentType || !contentType.includes('text/html')) {
console.log(`Non-HTML response: ${contentType}`)
return;
}
const HTMLText = await response.text();
return getURLsFromHTML(HTMLText, baseURL);
}