-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.js
executable file
·97 lines (79 loc) · 2.67 KB
/
index.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
#!/usr/bin/env node
const fs = require('fs-extra');
const path = require('path');
const puppeteer = require('puppeteer');
const configPath = process.argv.pop();
if (!configPath || !fs.existsSync(path.resolve(configPath))) {
console.error('Error: config not provided');
process.exit(1);
}
const tasks = require(path.resolve(configPath));
const DEFAULT_WIDTH = 1280;
const DEFAULT_HEIGHT = 800;
(async () => {
try {
await execute();
} catch (e) {
console.error(e);
process.exit(1);
}
async function execute() {
const browser = await puppeteer.launch();
const page = await browser.newPage();
for (const task of tasks) {
const { height, width, fullPage, emulate, auth, waitFor, element, routes } = task;
if (width || height) {
await page.setViewport({
width: width || DEFAULT_WIDTH,
height: height || DEFAULT_HEIGHT,
});
}
if (emulate) {
await page.emulate(puppeteer.KnownDevices[emulate]);
}
for (const route of routes) {
const { url, output } = route;
const outputPath = eval('`' + output + '`');
try {
if (!/\.pdf|\.jpg|\.jpeg|\.png$/.test(outputPath)) {
console.warn(`Warning: output format for ${output} is not supported`);
continue;
}
if (auth) {
const [username, password] = auth.split(';');
await page.authenticate({ username, password });
}
await page.goto(url);
if (waitFor) {
if (typeof waitFor === 'number') {
await page.waitFor(waitFor);
} else if (typeof waitFor === 'string') {
await page.waitForSelector(waitFor);
} else {
console.warn(`Warning: invalid waitFor value ${waitFor}`);
}
}
await fs.ensureDir(path.dirname(path.resolve(outputPath)));
if (element) {
const el = await page.$(element);
if (/\.pdf$/.test(outputPath)) {
console.warn('Warning: taking element screenshot in PDF not supported');
} else {
await el.screenshot({ path: path.resolve(outputPath) });
}
} else {
if (/\.pdf$/.test(outputPath)) {
await page.pdf({ path: path.resolve(outputPath) });
} else {
await page.screenshot({ path: path.resolve(outputPath), fullPage });
}
}
console.log(`Saved ${url} screenshot to ${outputPath}`);
} catch (e) {
console.error(`Failed to save ${url} screenshot to ${outputPath}`, e);
}
}
}
await browser.close();
}
})();