|
| 1 | +/* |
| 2 | +Copyright 2018 Google LLC |
| 3 | +
|
| 4 | +Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | +you may not use this file except in compliance with the License. |
| 6 | +You may obtain a copy of the License at |
| 7 | +
|
| 8 | + http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | +
|
| 10 | +Unless required by applicable law or agreed to in writing, software |
| 11 | +distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | +See the License for the specific language governing permissions and |
| 14 | +limitations under the License. |
| 15 | +*/ |
| 16 | +'use strict'; |
| 17 | + |
| 18 | +// [START full_sample] |
| 19 | +const express = require('express'); |
| 20 | +const puppeteer = require('puppeteer'); |
| 21 | +const app = express(); |
| 22 | + |
| 23 | +app.use(async (req, res) => { |
| 24 | + const url = req.query.url; |
| 25 | + |
| 26 | + if (!url) { |
| 27 | + return res.send('Please provide URL as GET parameter, for example: <a href="/?url=https://example.com">?url=https://example.com</a>'); |
| 28 | + } |
| 29 | + |
| 30 | + // [START browser] |
| 31 | + const browser = await puppeteer.launch({ |
| 32 | + args: ['--no-sandbox', '--disable-setuid-sandbox'] |
| 33 | + }); |
| 34 | + // [END browser] |
| 35 | + const page = await browser.newPage(); |
| 36 | + await page.goto(url); |
| 37 | + const imageBuffer = await page.screenshot(); |
| 38 | + await browser.close(); |
| 39 | + |
| 40 | + res.set('Content-Type', 'image/png'); |
| 41 | + res.send(imageBuffer); |
| 42 | +}); |
| 43 | + |
| 44 | +const server = app.listen(process.env.PORT || 8080, err => { |
| 45 | + if (err) return console.error(err); |
| 46 | + const port = server.address().port; |
| 47 | + console.info(`App listening on port ${port}`); |
| 48 | +}); |
| 49 | +// [END full_sample] |
| 50 | + |
| 51 | +module.exports = app; |
0 commit comments