-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
67 lines (60 loc) · 1.89 KB
/
server.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
const fs = require('fs');
const path = require('path');
const express = require('express');
const bodyParser = require('body-parser');
const chromeLauncher = require('chrome-launcher');
const screenshot = require(__dirname + '/src/lib/screenshot');
const debug = process.env.DEBUG || false;
const port = process.env.WEBPORT || 3000;
const chromeport = process.env.CHROMEPORT || 9222;
function launchHeadlessChrome() {
return chromeLauncher.launch({
port: chromeport,
chromeFlags: [
'--window-size=600,400',
'--disable-gpu',
'--headless'
]
});
}
const app = express()
app.use(bodyParser.urlencoded({ extended: true }));
app.get('/', (request, response) => {
response.sendFile('index.html', {
root: __dirname + '/src/views/',
dotfiles: 'deny',
headers: {
'content-type': 'text/html',
'x-timestamp': Date.now(),
'x-sent': true
}
});
});
app.post('/image', (request, response) => {
const { html, width, height, timeout } = request.body;
debug && console.log('Screenshot of image', width, height);
screenshot(html, width, height, timeout, chromeport, debug)
.then((data) => {
const buffer = new Buffer(data, 'base64');
response.type('png');
response.send(buffer);
})
.catch((err) => {
debug && console.error(err);
res.status(500).send({ error: err.message });
});
});
app.listen(port, (err) => {
if (err) {
console.error(err);
return true;
}
debug && console.log(`server is listening on ${port}`)
})
launchHeadlessChrome().then(chrome => {
debug && console.log(`Chrome debuggable on port: ${chrome.port}`);
process.on('exit', function() {
debug && console.log(`Killing Chrome on port: ${chrome.port}`);
chrome.kill();
});
});