Node and Delicious

In my last post, I wrote about using node.js as a scripting tool. Node has lots of good libraries for making network requests and processing the results. request is one of the most popular HTTP clients. It is easier to work with than the built-in http module that is designed to provide basic http client/server primitives.

Despite its chequered history, I recently started using delicious.com again for managing and sharing bookmarks for sites I want to remember. Modern browsers like Internet Explorer support synchronising bookmarks or favourites amongst your devices but I like the ability to store interesting sites in a public place so other people can see what I’m looking at (should they be interested!). This also allows me to find things that I stored from someone else’s device.

Delicious provides a variety of interesting APIs for developers but also some simple RSS or JSON data feeds.

Here is a simple node script that uses the request and querystring modules to retrieve the last 10 public bookmarks and creates a simple JSON output.

var request = require('request');
var qs = require('querystring');

var url = "http://feeds.delicious.com/v2/json/adrianba?";
var params = { count: 10 };
url += qs.stringify(params);
console.log(url);

request.get({url:url, json:true }, function (e, r, data) {
  var bookmarks = [];
  data.forEach(function(item) {
    var bookmark = {};
    bookmark.url = item.u;
    bookmark.text = item.d;
    bookmark.created = item.dt;
    bookmarks.push(bookmark);
  });
  console.log(JSON.stringify(bookmarks));
});

The important parts here are the use of request.get() which calls a callback when the response is retrieved and setting the json option to true so that the response JSON is already parsed when it is returned.

With just a few lines of code you can retrieve data with node and then do whatever processing you want on it.