Last active
September 2, 2021 23:47
-
-
Save petersooley/22f7d1d062a9a8fcd0422d9ec8b2b6c0 to your computer and use it in GitHub Desktop.
Gander: screenshot grabber service
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| { | |
| "name": "gander", | |
| "version": "1.0.0", | |
| "description": "Web service for getting screenshops of web sites", | |
| "main": "server.js", | |
| "scripts": { | |
| "start": "node server.js", | |
| "test": "npm run test" | |
| }, | |
| "author": "Peter Sooley <peter.sooley@downstream.com>", | |
| "license": "ISC", | |
| "dependencies": { | |
| "express": "^4.17.1", | |
| "puppeteer": "^1.18.1" | |
| } | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| const fs = require('fs') | |
| const path = require('path') | |
| const os = require('os') | |
| const express = require('express') | |
| const puppeteer = require('puppeteer') | |
| const app = express() | |
| const makeTempDir = function () { | |
| return new Promise((resolve, reject) => { | |
| fs.mkdtemp(path.join(os.tmpdir(), 'gander-'), (err, folder) => { | |
| if (err) { | |
| return reject(err) | |
| } | |
| return resolve(folder) | |
| }) | |
| }) | |
| } | |
| app.get('/snap', async function (req, res) { | |
| const { | |
| url, | |
| width = 1000, | |
| height = 563, | |
| format = 'png', // (or 'jpeg') | |
| filename = 'screenshot', | |
| } = req.query | |
| console.log(req.originalUrl, req.query) | |
| if (!url) { | |
| return res.status(400).send('Bad Request: missing `url` query parameter') | |
| } | |
| if (format !== 'png' && format !== 'jpeg') { | |
| return res.status(400).send(`Bad Request: invalid format value only 'png' or 'jpeg' are allowed`) | |
| } | |
| const dir = await makeTempDir() | |
| const path = `${dir}/${filename}.${format}` | |
| const browser = await puppeteer.launch() | |
| const page = await browser.newPage() | |
| await page.setViewport({ width, height, deviceScaleFactor: 1 }) | |
| await page.goto(url) | |
| await page.screenshot({ path, type: format }) | |
| await browser.close() | |
| res.sendFile(path) | |
| }) | |
| app.listen(3000) | |
| console.log('listening on port 3000') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment