Skip to content

Instantly share code, notes, and snippets.

@fmontes
Created April 1, 2022 21:49
Show Gist options
  • Star 20 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save fmontes/773f3f80978728fc380ee7f39bf57a5a to your computer and use it in GitHub Desktop.
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
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