Node.js: Expanding Shortened URLs
Join the DZone community and get the full member experience.
Join For Free
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); });
Published at DZone with permission of Axel Rauschmayer, DZone MVB. See the original article here.
Opinions expressed by DZone contributors are their own.
Comments