-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.js
52 lines (49 loc) · 1.28 KB
/
app.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
const os = require('os');
const NUM_BROWSERS = parseInt(process.argv[2], 10) || os.cpus().length;
const PORT = process.env.PORT || 3003
const Browser = require('./lib/Browser');
const Validate = require('./lib/Validate');
/*
* IMPORTANT - each browser is listening to process's "exit" event
* this line allows more than the default 10 listeners / browsers open at a time
*/
process.setMaxListeners(NUM_BROWSERS);
const browser = new Browser();
// Require the framework and instantiate it
const fastify = require('fastify')({
logger: {
customLevels: {
log: 35
}
}
});
/**
* @type {Validate}
*/
var validator;
// Declare a route
fastify.all('*', async (req, res) => {
let request = validator.parse(req, res);
if (!request) {
return;
}
let url = req.query.url;
try {
const picture = await browser.screenshot(url, request);
res.status(200)
.type(request.contentType)
.send(picture)
} catch (e) {
res.status(500)
.send(`Puppeteer Failed
- url: ${url}
- screenshot request: ${JSON.stringify(request)}
- stacktrace: \n\n${e.stack}`)
}
});
// Run the server!
fastify.listen(PORT, '0.0.0.0', (err, address) => {
if (err) throw err;
validator = new Validate({logger: fastify.log});
return browser.init(NUM_BROWSERS);
});