1 minute read

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.

<span class="kwrd">var</span> request = require(<span class="str">'request'</span>);
<span class="kwrd">var</span> qs = require(<span class="str">'querystring'</span>);

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

request.get({url:url, json:<span class="kwrd">true</span> }, <span class="kwrd">function</span> (e, r, data) {
  <span class="kwrd">var</span> bookmarks = [];
  data.forEach(<span class="kwrd">function</span>(item) {
    <span class="kwrd">var</span> 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.

Updated: