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

Tips, tricks and tools for creating your own data-driven app, 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);
});

 

Explore data-driven apps with less coding and query writing, 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.

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

{{ parent.tldr }}

{{ parent.urlSource.name }}