Created
May 5, 2012 17:53
-
-
Save deanmarano/2604354 to your computer and use it in GitHub Desktop.
Node.js URL unshortening function
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
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