Prajwal Tuladhar’s Blog
 
programming, life and some random thoughts

Dec 03 2009

Node.js: Changing the way we do I/O

Published by Prajwal Tuladhar at 11:30 pm under JavaScript

Node.js might be the most exciting single piece of software in the current JavaScript universe. Ryan received standing ovations for his talk and he really deserved it!

http://jsconf.eu/2009/video_nodejs_by_ryan_dahl.html

I tried Node.js last week and I was quite impress. Truly, Node.js has the potential to change the way we do I/O. Basically it’s an evented programming concept build on underlying stack of Python and C++ while using Google’s V8 (JavaScript Engine) as an interfacing language capable of performing network programming (using polling) in different way. Here are some of the key design goals of this technology:

  • No function should direct perform I/O (Use Callback to do so)
  • Stream everything, never force the buffering of data (Somewhat like comet)
  • Have built-in support for the most important protocols: HTTP, DNS, TCP
  • Support many HTTP features: Chunked requests, Keep-alive, Hang Requests for comet applications
  • Bridge API somewhere between flexibility of client side JavaScript and old Unix tools
  • Platform independent
Example:
Simple Twitter Client I wrote last week:

var http = require("http"),
	sys = require("sys");
var connection = http.createClient(80, "twitter.com");
var since_id = '';
var interval = 0;
function getTweets()	{
	var url = "/statuses/friends_timeline.json";
	if (since_id != '')	{
		url += "?since_id=" + since_id;
	}
	var request = connection.get(url, {
		"content-type": "application/json",
		"User-Agent": "NodeJS HTTP Client by Infynyxx",
		"host": "twitter.com",
		"Authorization": "Basic " + Base64.encode("infynyxx:*****")
	});
	request.finish(function(response)	{
		var responseBody = "";
		response.setBodyEncoding("utf8");
		response.addListener("body", function(chunk)	{
			responseBody += chunk;
		});
		response.addListener("complete", function()	{
			var tweets = JSON.parse(responseBody);
			if (tweets.error)	{
				sys.puts("Error: " + tweets.error);
			}
			else	{
				var length = tweets.length;
				if (length > 0)	{
					sys.puts("Getting new tweets...\n");
					sys.puts("Number of new tweets: " + length + "\n");
					var str = "";
					tweets.reverse();
					tweets.forEach(function(element, index) {
						str += element.text + "\n";
						str += element.user.name + "\n";;
						str += element.created_at + "\n";;
						str += "*************************\n";
					});
					sys.puts(str);
				}
			}
		});
	});
	setTimeout(getTweets, interval);
	interval = 300000;  //5 minutes
}

getTweets();

It also uses Base64 library. Full Code @ Gitgub


blog comments powered by Disqus

RSS Feed
Subscribe by email
Follow me @ Twitter