-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathapp.js
More file actions
102 lines (91 loc) · 2.34 KB
/
app.js
File metadata and controls
102 lines (91 loc) · 2.34 KB
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
98
99
100
101
102
var express = require('express');
var _ = require('lodash');
var path = require('path');
var puppeteer = require('puppeteer');
var expressServer;
//Default options
var config = {
port: 1337,
options: {
lineHeight: "40px",
fontSize: "25px",
width: "400px",
viewport: {
width: 400,
height: 800
}
},
callback: null,
googleAPIKey: ""
};
/**
* Start basic express server with ejs support, witch loads generator_phantom.html on / URL
*/
function startServer() {
//Set up express
var app = express();
app.engine('.html', require('ejs').__express);
app.set('view engine', 'html');
app.set('views', path.resolve(__dirname, 'generators'));
//Main page render entry point
app.get('/', function(req, res) {
var renderFile = 'generator_phantom.html';
var params = config.options;
params.googleAPIKey = config.googleAPIKey;
res.render(renderFile, params);
});
//start server
expressServer = app.listen(process.env.PORT || config.port);
console.log("Running server on port: " + config.port);
}
function takeScreenShotPuppeteer(url, callback) {
puppeteer.launch({ headless: true }).then(browser => {
browser.newPage()
.then(page => {
page.goto(url);
page.on('console', msg => {
console.log('PAGE LOG:', msg.text());
if (msg.text().startsWith('takeScreenshot')) {
page.setViewport({
width: config.options.viewport.width,
height: config.options.viewport.height
});
page.screenshot({
fullPage: true,
omitBackground: true
})
.then(buffer => {
browser.close();
callback(buffer);
});
}
});
})
});
}
function validateParameters(parms) {
if (!parms.googleAPIKey || !(typeof parms.googleAPIKey == 'string' || parms.googleAPIKey instanceof String) || parms.googleAPIKey.length <= 0) {
throw "Must supplay googleAPIKey";
}
}
/**
* Async returs image encoded as base64 string
*/
var getImage = function(_params) {
validateParameters(_params);
//merge configs
config = _.merge(config, _params);
//start basic express server using config.port
startServer();
//actually take screenshot with phantomjs
var pageUrl = "http://localhost:" + config.port;
takeScreenShotPuppeteer(pageUrl, function(imageString) {
expressServer.close();
_params.callback(imageString);
});
};
//Public stuff
var bootstrap = {
getImage: getImage
};
module.exports = bootstrap;