Created
October 13, 2019 12:23
-
-
Save Dirk94/1c236fc47c02d04e6371ded336ad0615 to your computer and use it in GitHub Desktop.
The Google Cloud function that can take screenshots of websites.
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 { Storage } = require('@google-cloud/storage'); | |
const GOOGLE_CLOUD_PROJECT_ID = "screenshotapi"; | |
const BUCKET_NAME = "screenshot-api-net"; | |
exports.run = async (req, res) => { | |
res.setHeader("content-type", "application/json"); | |
try { | |
const buffer = await takeScreenshot(req.body); | |
let screenshotUrl = await uploadToGoogleCloud(buffer, "screenshot.png"); | |
res.status(200).send(JSON.stringify({ | |
'screenshotUrl': screenshotUrl | |
})); | |
} catch(error) { | |
res.status(422).send(JSON.stringify({ | |
error: error.message, | |
})); | |
} | |
}; | |
async function uploadToGoogleCloud(buffer, filename) { | |
const storage = new Storage({ | |
projectId: GOOGLE_CLOUD_PROJECT_ID, | |
}); | |
const bucket = storage.bucket(BUCKET_NAME); | |
const file = bucket.file(filename); | |
await uploadBuffer(file, buffer, filename); | |
await file.makePublic(); | |
return `https://${BUCKET_NAME}.storage.googleapis.com/${filename}`; | |
} | |
async function takeScreenshot(params) { | |
const browser = await puppeteer.launch({ | |
args: ['--no-sandbox'] | |
}); | |
const page = await browser.newPage(); | |
await page.goto(params.url, {waitUntil: 'networkidle2'}); | |
const buffer = await page.screenshot(); | |
await page.close(); | |
await browser.close(); | |
return buffer; | |
} | |
async function uploadBuffer(file, buffer, filename) { | |
return new Promise((resolve) => { | |
file.save(buffer, { destination: filename }, () => { | |
resolve(); | |
}); | |
}) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment