public
Last active

  • Download Gist
example.js
JavaScript
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42
var http = require('http'),
url = require('url');
 
var server = http.createServer(onRequest)
server.listen(8888);
 
function onRequest(request, response) {
var parsedUrl = url.parse(request.url, true),
urlToExpand = parsedUrl.query.url;
expand(urlToExpand, writeResponse);
function writeResponse(error, newUrl) {
if (error) {
response.writeHead(500, { 'Content-Type': 'text/plain'});
return response.end(error.message);
}
response.writeHead(200, { 'Content-Type': 'text/plain'});
response.end(newUrl);
}
}
 
function expand(urlToParse, callback) {
var short = url.parse(urlToParse);
var options = {
host: short.hostname,
port: 80,
path: short.pathname
};
var clientRequest = http.get(options, extractRealURL);
clientRequest.on("error", forwardError);
function extractRealURL(res) {
callback(null, res.headers.location);
}
function forwardError(error) {
callback(err);
}
}

This code fails if you do not enter a url parameter. You need to check if parsedUrl.query.url is defined before continuing with call to expand(urlToExpand, writeResponse);

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.