Create a gist now

Instantly share code, notes, and snippets.

var http = require('http'),
url = require('url');
var server = http.createServer(onRequest)
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'});
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) {

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);

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment