Created
April 1, 2022 21:49
-
-
Save fmontes/773f3f80978728fc380ee7f39bf57a5a to your computer and use it in GitHub Desktop.
Server to return a screenhot of the page you pass in the URL like: http://localhost:3000/?url=https://demo.dotcms.com
This file contains 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 puppeteer = require('puppeteer'); | |
const http = require('http'); | |
const url = require('url'); | |
const requestListener = async function (req, res) { | |
try { | |
const { href } = new URL(url.parse(req.url, true).query.url); | |
const browser = await puppeteer.launch(); | |
const page = await browser.newPage(); | |
await page.setViewport({ width: 1024, height: 768 }); | |
await page.goto(href); | |
const b64string = await page.screenshot({ encoding: "base64" }); | |
const buffer = Buffer.from(b64string, "base64"); | |
res.writeHead(200, { | |
'Content-Type': 'image/png', | |
'Content-Length': buffer.length | |
}); | |
res.end(buffer); | |
await browser.close(); | |
} catch { | |
res.statusCode = 400; | |
res.end('Url is bad') | |
} | |
} | |
const server = http.createServer(requestListener); | |
server.listen(3000); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment