-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcrawl.js
More file actions
89 lines (74 loc) · 2.1 KB
/
crawl.js
File metadata and controls
89 lines (74 loc) · 2.1 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
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
const {JSDOM} = require('jsdom')
async function crawlPage(baseUrl, currentUrl, pages) {
const currentUrlObj = new URL(currentUrl)
const baseUrlObj = new URL(baseUrl)
if (currentUrlObj.hostname !== baseUrlObj.hostname) {
return pages
}
const normalizedURL = normalizeURL(currentUrl)
if (pages[normalizedURL] > 0) {
pages[normalizedURL]++
return pages
}
if (currentUrl === baseUrl) {
pages[normalizedURL] = 0
} else {
pages[normalizedURL] = 1
}
let htmlBody = ''
console.log(`crawling ${currentUrl}`)
try {
const resp = await fetch(currentUrl)
if (resp.status > 399){
console.log(`HTTP Err, status code: ${resp.status}`)
return pages
}
const contentType = resp.headers.get('content-type')
if (!contentType.includes('text/html')) {
console.log(`HTTP Err, content-type: ${contentType}`)
return pages
}
htmlBody = await resp.text()
} catch (err) {
console.log(err.message)
}
const nextUrls = getURLfromHTML(htmlBody, baseUrl)
for (const nextUrl of nextUrls) {
pages = await crawlPage(baseUrl, nextUrl, pages)
}
return pages
}
function normalizeURL(url) {
const urlObj = new URL(url)
let fullPath = `${urlObj.host}${urlObj.pathname}`
if (fullPath.length > 0 && fullPath.slice(-1) === '/'){
fullPath = fullPath.slice(0, -1)
}
return fullPath
}
function getURLfromHTML(htmlBody, baseUrl) {
const urls = []
const domObj = new JSDOM(htmlBody)
const domArr = domObj.window.document.querySelectorAll('a')
for (const dA of domArr) {
if (dA.href.slice(0,1) === '/'){
try {
urls.push(new URL(dA.href, baseUrl).href)
} catch (err) {
console.log(`${err.message}: ${dA.href}`)
}
} else {
try {
urls.push(new URL(dA.href).href)
} catch (err) {
console.log(`${err.message}: ${dA.href}`)
}
}
}
return urls
}
module.exports = {
crawlPage,
normalizeURL,
getURLfromHTML
}