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.
npm install requestThat 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); }); }
npm install qThe “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); });