Messing around with Node.js and HTTP

Post to Twitter

I’ve done a few articles/tutorials on using Node.js. Today though I’m going to simply build a simple HTTP server that returns some useful information.


[ad name=”Google Adsense”]

You need to make sure you have Node.js installed, I’m using it on Ubuntu 10.04 via VMWare on a Windows 7 computer. Once your Node.js is working you can open your favorite editor and enter this code:

var sys = require('sys'),
   http = require('http'),
	url = require('url');

http.createServer(incomingRequest).listen(8000);
sys.puts('Server running at http://127.0.0.1:8000/');

function incomingRequest(req, res)
{
    var ipAddress = null;
    var parsedURL = null;
	var webkitCheck = '';

    try
    {
    	parsedURL = url.parse(req.url, true);
		ipAddress = req.connection.remoteAddress;

		sys.puts('IP Address: ' + ipAddress);
		sys.puts('\n');
		sys.puts(sys.inspect(req.headers, false));
		sys.puts('\n');
		sys.puts(sys.inspect(parsedURL, false));
		sys.puts('\n' + parsedURL.query['name']);
		sys.puts('user-agent: ' + req.headers['user-agent']);
		sys.puts('\n');

		webkitCheck = req.headers['user-agent'].toLowerCase();

		if(webkitCheck.indexOf('chrome') != -1)
		{
			sys.puts("Your using Chrome");
		}
		else
		{
			sys.puts("Your not using Chrome");
		}
    }
    catch (error)
    {
		sys.puts("Error: " + error);
    }

	res.writeHead(200, {'Content-Type': 'text/html'});
    res.write('<br/><strong>Hello World...</strong>');
    res.end();
    process.exit();
}

The code is a little verbose but I wanted it to be very clear and easy to understand what I’m doing. When an HTTP request comes in it’s handed off to the incomingRequest function. The first thing I do is parse the URL and get the user’s IP address. From here I just print out some information all web developers are familiar with but might not know how to do this in node.js. I check the querystring to see if a parameter called “name” has a value, if so that is printed out. Another thing I did was check if the user is using Google’s Chrome browser or not. The last thing I ended up doing was closing down the server, obviously if you wanted to the server to keep running you could remove the call to: process.exit();

Here are the results when running from Chrome:

…and the output from the Terminal window (click on image to enlarge):

[ad name=”Google Adsense – large sqr rounded”]

Post to Twitter

This entry was posted in JavaScript, Node.js, Open Source, Ubuntu. Bookmark the permalink.

One Response to Messing around with Node.js and HTTP

  1. ash says:

    FYI, for others trying to determine what fields are inside req.headers:
    for(var prop in req.headers)
    sys.puts(prop);

Comments are closed.