Node.js: expanding shortened URLs
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) {
return Q.ncall(request, null, {
method: "HEAD",
url: shortUrl,
followAllRedirects: true
// If a callback receives more than one (non-error) argument
// then the promised value is an array. We want element 0.
}).get('0').get('request').get('href');
}
Node that the callback created by
deferred.node() automatically handles errors. Invoking the function works like this:
expandUrl("http://t.co/Zc3cUoly")
.then(function (longUrl) {
console.log(longUrl);
});
Related reading