This repository has been archived by the owner on Mar 21, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.mjs
72 lines (61 loc) · 1.89 KB
/
index.mjs
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
import express from 'express';
import bodyParser from 'body-parser';
import puppeteer from 'puppeteer';
(async () => {
const serverPort = 3000;
const app = express();
app.use(bodyParser.json());
const browser = await puppeteer.launch({args: ['--no-sandbox', '--disable-setuid-sandbox']});
async function takeScreenshot(browser, options, url) {
try {
var page = await browser.newPage();
await page.setViewport(options);
await page.goto(url);
const screenshot = await page.screenshot();
if (page) {
await page.close();
} return screenshot
} catch (e) {
if (page) {
await page.close();
}
throw e;
}
}
app.post('/', async (req, res) => {
try {
const options = {
width: req.body.width || 1024,
height: req.body.height || 1301,
isMobile: req.body.isMobile || false,
};
console.log('options ', {...options, url: req.body.url});
const png = await Promise.race([
takeScreenshot(browser, options, req.body.url),
new Promise((resolve, reject) => setTimeout(reject, 15 * 1000, Error('timeout reached')))
]);
res.set('Content-Type', 'image/png');
res.end(png, 'binary');
} catch (e) {
res.status(500).send(e.message);
console.log('error', e);
}
});
const server = app.listen(serverPort);
// HTTP Keep-Alive to a short time to allow graceful shutdown
server.on('connection', function (socket) {
socket.setTimeout(20 * 1000);
});
const shutdown = async () => {
console.log('graceful shutdown puppeteer');
await browser.close();
console.log('graceful shutdown express');
server.close(function () {
console.log('closed express');
process.exit();
});
};
process.on('SIGINT', shutdown);
process.on('SIGTERM', shutdown);
console.log('Running server: http://0.0.0.0:' + serverPort);
})();