Skip to content

Instantly share code, notes, and snippets.

@deanmarano
Created May 5, 2012 17:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save deanmarano/2604354 to your computer and use it in GitHub Desktop.
Save deanmarano/2604354 to your computer and use it in GitHub Desktop.
Node.js URL unshortening function
var http = require("http"),
url = require("url");
function unshortenUrl(unshortedUrl, returnFunction) {
var urlObj = url.parse(unshortedUrl);
var options = {
host: urlObj.host,
port: urlObj.port,
path: urlObj.pathname
};
var req = http.request(options, function(res) {
var headers = res.headers;
res.setEncoding('utf8');
if(headers.location === undefined) {
returnFunction(unshortedUrl);
}
else {
if(headers.location.indexOf('/') === 0) {
returnFunction(unshortedUrl);
return;
}
unshortenUrl(headers.location, returnFunction);
}
});
req.on('error', function(e) {
console.log('problem with request: ' + e.message);
returnFunction(unshortedUrl);
});
req.write('data\n');
req.end();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment