Hoorah Node.js!

Several months ago, I had a look at Node.js, just for fun.  I was getting more into JavaScript and thought it looked neat.  I didn’t do a lot with it, but I did go through a tutorial to build a web server that did math equations.  Nothing fancy.

Flash forward to today.

I’m working on an Android project where I need to download some JSON from a client’s server.  They asked for my IP earlier in the week so they could set me up with access.  Sadly, my busy life these days meant I couldn’t get to the project until Saturday, when lo and behold, I don’t have access to the server.  And it won’t be up until Monday, which makes the data download/parsing work I planned on doing a little harder.

Well, then I decided I would just put up the data on my web server, but then it’s coming as HTML (unless I mess around with it) which isn’t quite as realisitc.  Then I remembered Node.js, so I went back to it, fiddled about 10 minutes, and voila!  I had a web server that would distribute my JSON, and also show that it is receiving the proper query.  Plus, I got to mess around with Node, which is just a fun thing to do when you’re working on the weekend. :)

Here’s the code I wrote, which shows how easy it is to do quick server-y kind of stuff with Node.  It could have been done even faster if it was more fresh in my mind.

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

var serverIP = "192.168.1.100";
var port = 3001;

http.createServer(function(req,res){
	res.writeHead(200, {'Content-Type':'application/json'});

	var q = querystring.parse( url.parse( req.url ).query );
        // write the query to the console.
	sys.puts( JSON.stringify( q ) );
	var s = {};
	if( q.t && q.t != "nw" ) {
	   s = { t : "now",
	        p : [ ..customer stuff.. ],
                c : [ ..more customer stuff.. ]
           };
	}

	res.end( JSON.stringify( s ) );
}).listen(port, serverIP);

sys.puts("Server running at http://" + serverIP + ":" + port + "/");

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>