Last active
September 21, 2017 20:46
-
-
Save steren/2f7ca965dce87e7d9c40540142eb23ea to your computer and use it in GitHub Desktop.
Node.js app to generate a thumbnail of the given URL
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": "web-thumbnails", | |
"version": "1.0.0", | |
"engines": { | |
"node": "^8.4.0" | |
}, | |
"description": "Generate thumbnails of web pages", | |
"main": "server.js", | |
"scripts": { | |
"start": "node server.js", | |
"test": "echo \"Error: no test specified\" && exit 1" | |
}, | |
"author": "[email protected]", | |
"license": "ISC", | |
"dependencies": { | |
"express": "^4.15.4", | |
"puppeteer": "^0.10.2" | |
} | |
} |
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 puppeteer = require('puppeteer'); | |
const express = require('express'); | |
const app = express(); | |
app.use(async (req, res) => { | |
if(req.path === '/') {res.end('Please provide URL');} | |
const url = req.path.slice(1); | |
console.log(`URL: ${url}`); | |
const browser = await puppeteer.launch(); | |
const page = await browser.newPage(); | |
await page.goto(url); | |
let imageBuffer = await page.screenshot(); | |
await browser.close(); | |
res.set('Content-Type', 'image/png') | |
res.end(imageBuffer); | |
}) | |
const server = app.listen(process.env.PORT || 3000, err => { | |
if (err) return console.error(err); | |
const port = server.address().port; | |
console.log(`App listening on port ${port}`); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment