-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpage-loader.js
179 lines (143 loc) · 4.41 KB
/
page-loader.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
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
import setNamespace from 'debug';
import axios from 'axios';
import path from 'path';
import fs from 'fs/promises';
import process from 'process';
import cheerio from 'cheerio';
import mime from 'mime-types';
import { createWriteStream } from 'fs';
const debug = setNamespace('page-loader');
let $;
class PageLoader {
#url;
#outputDir;
#resourceDir;
constructor(urlString, outputDir) {
this.#url = new URL(urlString);
this.#outputDir = this.#normalizeDirPath(outputDir);
this.#resourceDir = `${this.#generateFileName(this.#url.href)}_files`;
}
async load() {
await this.#loadDom();
await this.#ensureDirExists(this.#outputDir);
await this.#createResourceDir();
await this.#loadResources();
const filepath = await this.#saveHtml();
return { filepath };
}
async #saveHtml() {
const htmlFilename = this.#generateFileName(this.#url.href) + '.html';
const filepath = path.join(this.#outputDir, htmlFilename);
await fs.writeFile(filepath, $.html());
return filepath;
}
async #ensureDirExists(dirPath) {
try {
await fs.access(dirPath);
} catch (error) {
if (error.code === 'ENOENT') {
await fs.mkdir(dirPath, { recursive: true });
} else {
throw error;
}
}
}
#normalizeDirPath(pathToFolder) {
return path.resolve(process.cwd(), pathToFolder);
}
async #createResourceDir() {
await fs.mkdir(path.join(this.#outputDir, this.#resourceDir), { recursive: true });
}
async #loadDom() {
const { data } = await axios.get(this.#url.toString());
$ = cheerio.load(data);
}
async #loadResources() {
const $links = $('link');
const $images = $('img');
const $scripts = $('script');
const results = await Promise.allSettled(
[$links, $images, $scripts].flatMap(($elements) =>
$elements.toArray().reduce((promises, el) => {
const resourceUrl = this.#getResourceUrl(el);
if (!this.#isResourceLocal(resourceUrl)) {
return promises;
}
return promises.concat(
this.#loadResource(resourceUrl.href).then((resp) => ({ el, resp })),
);
}, []),
),
);
await Promise.allSettled(
results
.reduce((acc, res) => (res.value ? acc.concat(res.value) : acc), [])
.map(({ el, resp }) => {
const { url } = resp.config;
const extname = path.extname(url) || `.${mime.extension(resp.headers['content-type'])}`;
const resourcePath = this.#getResourceFilePath(url, extname);
this.#changeElementUrl(el, resourcePath);
return this.#saveResource(resp.data, path.join(this.#outputDir, resourcePath));
}),
);
}
#getResourceUrl(element) {
const urlAttr = this.#getUrlAttr(element);
return new URL(element.attribs[urlAttr], this.#url.href);
}
#isResourceLocal(resourceUrl) {
return resourceUrl.origin === this.#url.origin;
}
async #loadResource(url) {
try {
const resp = await axios.get(url, { responseType: 'stream' });
return resp;
} catch (error) {
console.error(`Error downloading ${url}`, error);
throw error;
}
}
#changeElementUrl(element, newUrl) {
const urlAttr = this.#getUrlAttr(element);
$(element).attr(urlAttr, newUrl);
}
async #saveResource(data, path) {
const writer = createWriteStream(path);
data.pipe(writer);
debug(`start writing to path: ${path}`);
return new Promise((resolve, reject) => {
writer.on('finish', () => {
debug(`finish writing to path: ${path}`);
resolve();
});
writer.on('error', (error) => {
debug(`error writing to path: ${path}\n`, error);
reject(error);
});
});
}
#getUrlAttr(element) {
return element.name === 'link' ? 'href' : 'src';
}
#getResourceFilePath(rawName, extname) {
return path.join(this.#resourceDir, this.#generateFileName(rawName, extname));
}
#generateFileName(string, extname = null) {
const regex = new RegExp(`${extname ? `(?!\\${extname})` : ''}[^a-z0-9]`, 'gi');
let filename = string
.trim()
.replace(/^https?:\/\//, '')
.replace(regex, '-');
if (extname && !path.extname(filename)) {
filename = filename.concat(extname);
}
return filename;
}
}
const loadPage = (url, destFolder) => {
return new PageLoader(url, destFolder).load();
};
module.exports = {
PageLoader,
loadPage,
};