This repository has been archived by the owner on Jul 19, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcrawl.js
82 lines (67 loc) · 1.78 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
import { urlToHttpOptions } from "node:url"
import { JSDOM } from "jsdom"
async function crawlPage(baseURL, currURL = baseURL, pages = {}) {
let currURLObj = new URL(currURL)
let baseURLObj = new URL(baseURL)
if (baseURLObj.origin != currURLObj.origin) {
return pages
}
const normalizedURL = normalizeURL(currURL)
if (pages[normalizedURL] > 0) {
pages[normalizedURL]++
return pages
}
pages[normalizedURL] = 1
console.log(`Now crawling: ${currURL}`)
let html = ""
try {
html = await fetchHTML(currURL)
} catch (err) {
console.log(`Error: ${err.message}`)
return pages
}
const nextURLs = getURLsFromHTML(html, baseURL)
for (const url of nextURLs) {
pages = await crawlPage(baseURL, url, pages)
}
return pages
}
async function fetchHTML(url) {
let res
try {
res = await fetch(url)
} catch (err) {
throw new Error(`Got Network error: ${err.message}`)
}
if (res.status > 399) {
throw new Error(`Got HTTP error: ${res.status} ${res.statusText}`)
}
const contentType = res.headers.get("content-type")
if (!contentType || !contentType.includes("text/html")) {
throw new Error(`Got non-HTML response: ${contentType}`)
}
return res.text()
}
function normalizeURL(rawURL) {
let myURL = new URL(rawURL)
let props = urlToHttpOptions(myURL)
let fullURL = props.hostname + props.pathname
if (fullURL[fullURL.length - 1] === "/") {
return fullURL.slice(0, fullURL.length - 1)
}
return fullURL
}
function getURLsFromHTML(htmlBody, baseURL) {
const dom = new JSDOM(htmlBody)
const atags = dom.window.document.querySelectorAll("a")
const hrefs = []
for (let link of atags) {
let href = link.getAttribute("href")
if (href.startsWith("/")) {
href = baseURL + href
}
hrefs.push(href)
}
return hrefs
}
export { normalizeURL, getURLsFromHTML, crawlPage }