-
Notifications
You must be signed in to change notification settings - Fork 0
/
prerender.js
59 lines (48 loc) · 1.49 KB
/
prerender.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
const Puppeteer = require('puppeteer');
const Express = require('express');
const { join, dirname } = require('path');
const { readFile, exists, writeFile, mkdir } = require('mz/fs');
const PORT = 4000;
const HOST = `http://localhost:${PORT}`;
const ROOT_PATH = 'dist/gdg-website';
const STATIC_PATHS = require('./static-paths');
async function main() {
const app = Express();
const index = (await readFile(
join(process.cwd(), ROOT_PATH, 'index.html')
)).toString();
app.get('*.*', Express.static(join(process.cwd(), ROOT_PATH)));
app.get('*', (req, res) => res.send(index));
const server = await new Promise((resolve, reject) => {
const createdServer = app.listen(PORT, error =>
error ? reject(error) : resolve(createdServer)
);
});
const browser = await Puppeteer.launch();
const page = await browser.newPage();
for (const currentPath of STATIC_PATHS.PATHS) {
await page.goto(`${HOST}/${currentPath}`);
let result = await page.evaluate(
() => '<!doctype html>' + document.documentElement.outerHTML
);
const file = join(
process.cwd(),
ROOT_PATH,
(currentPath || 'index') + '.html'
);
const dir = dirname(file);
if (!(await exists(dir))) {
await mkdir(dir);
}
await writeFile(file, result);
console.log('Written file:', file);
}
browser.close();
server.close();
}
main()
.then(() => console.log('All right!'))
.catch(error => {
console.error('Error:', error);
process.exit(1);
});