Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Node.js: Expanding Shortened URLs

DZone's Guide to

Node.js: Expanding Shortened URLs

· Web Dev Zone
Free Resource

Start coding today to experience the powerful engine that drives data application’s development, brought to you in partnership with Qlik.

This blog post explains how one can use Node.js to expand a URL that has been shortened by a service such as t.co (built into Twitter) and bit.ly. We’ll look at a simple implementation and at an advanced implementation that uses promises.

 

The minimum

You need to install Mikeal Rogers’ request module:

npm install request

That module automatically follows all redirects from the shortened URL. Once you are at your final destination, you only need to find out where you are:

var request = require("request");

function expandUrl(shortUrl) {
    request( { method: "HEAD", url: shortUrl, followAllRedirects: true },
        function (error, response) {
            console.log(response.request.href);
        });
}

Prettier with promises

If you want to write a function that returns the expanded URL, more work is needed. You have the option of using a callback, but promises usually lead to prettier code. Let’s use Kris Kowal’s Q module:

npm install q

The “promising” code looks as follows.

var Q = require("q");
var request = require("request");

function expandUrl(shortUrl) {
    var deferred = Q.defer();
    request( { method: "HEAD", url: shortUrl, followAllRedirects: true },
        function (error, response) {
            if (error) {
                deferred.reject(new Error(error));
            } else {
                deferred.resolve(response.request.href);
            }
        });
    return deferred.promise;
}

Invoking the function works like this: 

expandUrl("http://example.com")
.then(function (longUrl) {
    console.log(longUrl);
});

 

Create data driven applications in Qlik’s free and easy to use coding environment, brought to you in partnership with Qlik.

Topics:

Published at DZone with permission of Axel Rauschmayer, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

THE DZONE NEWSLETTER

Dev Resources & Solutions Straight to Your Inbox

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

X

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}