-
Notifications
You must be signed in to change notification settings - Fork 3
/
url_parser.ts
44 lines (35 loc) · 1020 Bytes
/
url_parser.ts
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
import { blue, bold } from "https://deno.land/std/fmt/colors.ts";
class UrlParser {
static readonly LINK_REGEX_BASE =
'((?<=src=")|(?<=href="))([\\/.:-\\d\\w]+\\.(TYPE))';
url: string;
file_types: Array<string>;
html = "";
constructor(url: string, file_types: Array<string>) {
this.url = url;
this.file_types = file_types;
}
async links(): Promise<Array<string>> {
await this.scrape();
const linkRegex = new RegExp(
UrlParser.LINK_REGEX_BASE.replace("TYPE", this.file_types.join("|")),
"g",
);
const matches = [...this.html.matchAll(linkRegex)];
const urls = matches.map((match: RegExpMatchArray) => match[0]);
const unique = [...new Set(urls)];
return unique;
}
private async scrape() {
console.log(
bold(
blue(
`Scraping ${this.url} for ${this.file_types.join(", ")} files ...`,
),
),
);
const res = await fetch(this.url);
this.html = await res.text();
}
}
export default UrlParser;