-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindexold.js
64 lines (51 loc) · 1.35 KB
/
indexold.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
const express = require('express')
const puppeteer = require('puppeteer-core')
const app = express()
const port = process.env.PORT || 3000
const cache = {}
app.get('/snap', async (req, res) => {
let browser = null
let page = null
try {
let url = decodeURIComponent(req.query.url)
// Check if the screenshot is already cached
if (cache[url]) {
console.log('Serving from cache:', url)
res.set('Content-Type', 'image/jpeg')
res.send(cache[url])
return
}
// Prepend "http://" if the URL doesn't start with a protocol
if (!(/^https?:\/\//i).test(url)) {
url = `http://` + url
}
browser = await puppeteer.launch()
page = await browser.newPage()
// Set a custom viewport size
await page.setViewport({ width: 1920, height: 1080 })
// Go to the URL
await page.goto(url)
// Take a screenshot
const screenshot = await page.screenshot({
path: 'screenshot.png'
})
cache[url] = screenshot
res.set('Content-Type', 'image/jpeg')
res.send(screenshot)
} catch (error) {
console.error(error)
res
.status(500)
.json({ error: 'An error occurred while capturing the screenshot' })
} finally {
if (page) {
await page.close()
}
if (browser) {
await browser.close()
}
}
})
app.listen(port, () => {
console.log(`Server running on port` + port)
})