Created
April 26, 2016 07:33
Star
You must be signed in to star a gist
OGP Fetch API for AWS Lambda
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
'use strict'; | |
console.log('Loading function'); | |
const http = require('http'); | |
const https = require('https'); | |
const regexs = [ | |
new RegExp('<meta property=["\']og:title["\'] content=["\']([^>]+)["\']', 'i'), | |
new RegExp('<meta content=["\']([^>]+)["\'] property=["\']og:title["\']', 'i'), | |
new RegExp('<title>([^<]*)</title>', 'i'), | |
]; | |
exports.handler = (event, context, callback) => { | |
console.log('Received event:', JSON.stringify(event, null, 2)); | |
const url = event.url; | |
const module = url.indexOf('https://') !== -1 ? https : http; | |
module.get(url, function(res) { | |
var body = ''; | |
res.setEncoding('utf8'); | |
res.on('data', function(chunk) { | |
body += chunk; | |
}); | |
res.on('end', function() { | |
for (var i = 0; i < regexs.length; i ++) { | |
var regex = regexs[i]; | |
var match = regex.exec(body); | |
if (match && match[1]) { | |
callback(null, {"url": url, "title": match[1]}); | |
return | |
} | |
} | |
callback(null, {"url": url, "title": ""}); | |
}); | |
}).on('error', function(e) { | |
callback(null, {"url": url, "title": "", "error": e.message}); | |
}); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment