Skip to content

Instantly share code, notes, and snippets.

@daithiw44
Created September 4, 2012 22:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save daithiw44/3627484 to your computer and use it in GitHub Desktop.
Save daithiw44/3627484 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.
/*
* 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