-
-
Save gotomypc/3967454 to your computer and use it in GitHub Desktop.
Twitter GET users/profile_image/:screen_name, Nodejs get latest user profile_image output as a base64 encoded data URI, avoid the 302 redirect of the call with request module.
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
/* | |
* Access the profile image (Twitter GET users/profile_image/:screen_name) for a user with the indicated screen_name. | |
* Currently this resource does not return JSON (or XML), but instead returns a 302 redirect to the actual image resource. | |
* Use requests request.head with option followRedirect set to false to get the image file name from the json in the header response. | |
* Using the image file URL get the profile image and convert to base64 encoding to use as in this example as data URI (which could be saved to a DB/storage etc for later use etc). | |
* example call : http://127.0.0.1:4444/?screen_name=daithi44 | |
*/ | |
var http = require('http'), | |
request = require('request'), | |
url = require('url'); | |
http.createServer(function (req, res) { | |
var twitterwho = url.parse(req.url, true).query; | |
if (twitterwho.hasOwnProperty('screen_name')) { | |
request.head({ | |
uri: 'http://api.twitter.com/1/users/profile_image?screen_name=' + twitterwho.screen_name + '&size=normal', | |
followRedirect: false | |
}, function (error, imageresponse) { | |
var regex, imageuri, imagedata, base64, prefix, requestImg, data; | |
if (!error && imageresponse.statusCode === 302) { | |
regex = new RegExp('https://'); | |
imageuri = imageresponse.headers.location.replace(regex, 'http://'); | |
requestImg = http.get(imageuri, function (res64) { | |
prefix = 'data:' + res64.headers['content-type'] + ';base64,'; | |
imagedata = ''; | |
res64.setEncoding('binary'); | |
res64.on('data', function (chunk) { | |
imagedata += chunk; | |
}); | |
res64.on('end', function () { | |
base64 = new Buffer(imagedata, 'binary').toString('base64'); | |
data = prefix + base64; | |
res.writeHead(200, { | |
'Content-Type': 'text/html' | |
}); | |
res.end('<img src="' + data + '"/>'); | |
}); | |
}); | |
} else { | |
displayThis(); | |
} | |
}); | |
} else { | |
displayThis(); | |
} | |
function displayThis() { | |
res.writeHead(200, { | |
'Content-Type': 'text/plain' | |
}); | |
res.end('something else'); | |
} | |
}).listen(4444); | |
console.log('Server running at http://127.0.0.1:4444/'); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment