From 882c43f9417ed462b96b72165c26b7c8356787ca Mon Sep 17 00:00:00 2001 From: Steren Date: Wed, 12 Sep 2018 14:08:29 -0700 Subject: [PATCH] Headless Chrome: keep browser alive between requests. (#675) Headless Chrome: keep browser alive between requests. --- appengine/headless-chrome/app.js | 35 ++++++++++++++++++++------------ 1 file changed, 22 insertions(+), 13 deletions(-) diff --git a/appengine/headless-chrome/app.js b/appengine/headless-chrome/app.js index 8a98d0b904f..9d3219197bf 100644 --- a/appengine/headless-chrome/app.js +++ b/appengine/headless-chrome/app.js @@ -20,6 +20,27 @@ const express = require('express'); const puppeteer = require('puppeteer'); const app = express(); +let browser; + +async function init () { + // [START browser] + browser = await puppeteer.launch({ + args: ['--no-sandbox'] + }); + // [END browser] + + const server = app.listen(process.env.PORT || 8080, async err => { + if (err) { + await browser.close(); + return console.error(err); + } + const port = server.address().port; + console.info(`App listening on port ${port}`); + }); +} + +init(); + app.use(async (req, res) => { const url = req.query.url; @@ -27,25 +48,13 @@ app.use(async (req, res) => { return res.send('Please provide URL as GET parameter, for example: ?url=https://example.com'); } - // [START browser] - const browser = await puppeteer.launch({ - args: ['--no-sandbox'] - }); - // [END browser] - const page = await browser.newPage(); + let page = await browser.newPage(); await page.goto(url); const imageBuffer = await page.screenshot(); - browser.close(); res.set('Content-Type', 'image/png'); res.send(imageBuffer); }); - -const server = app.listen(process.env.PORT || 8080, err => { - if (err) return console.error(err); - const port = server.address().port; - console.info(`App listening on port ${port}`); -}); // [END full_sample] module.exports = app;