All about programming in GNU/LINUX

Writing A Simple WebServer using NODEJS

Well , we should consider ourselves lucky to be in this age of computing where a programmers job is made very easy with usage of modern languages . Writing a Web Server using C was and is a herculian task . With issues like limited buffer size , spawing threads or new processes to cater new clients and bulky system calls with complex structures to pass as parameters everthing has to be explicitly managed . One of the easiest way which i’ve found out to write webservers is by using NODEJS . Concurrency handling mechanisms are taken care of implicitly and programming becomes easy since Java Script is used .Here is a simple webserver written using NODEJS

var http=require('http'),
	url = require('url'),
	mime = require('mime'),//npm install mime
	fs = require('fs'),
	search_path='/home/karthic/mydata/codes';
http.createServer(function(req,res) { 
	 pathname = search_path + req.url;
	 console.log(pathname);

	fs.stat(pathname , function(err,stats){
	  if(err) { 
		res.writeHead(404);
		res.write('Bad Request , Request cannot be accepted');
		res.end()
		}
	else if(stats.isFile()) {
		//content-type
		var type = mime.lookup(pathname);
		console.log(type);
		res.setHeader('Content-Type',type);

		// 200 status - found , no errors 
		res.statusCode = 200;
	
		//create a readable stream and pipe to the http response 
		var file = fs.createReadStream(pathname);
		file.on("open",function() { 
			file.pipe(res);
		});
		file.on("error",function(err) {
			cosole.log(err);
		});
	     }
	else {
		res.writeHead(403);
		res.write('Cannot Access Directory');
		res.end();
		}
	});
}).listen(8324);//listen to port 8324
console.log('Server running at 8324');
		
Advertisements

2 responses

  1. Pingback: Sending data to the Node.JS server using WebSockets | hackintoshrao

  2. Оh my goodness! Awesome article dude! Мany tҺanks, Howеver I am going throuɡh problеms with
    your RSS. I don’t қnow the reason why І am unable
    tօ join it. Is thеre anybody having simіlar RSS issues?
    Аnyone that ƙnows the solution caan youu kindly respond? Тhanks!!

    May 18, 2014 at 3:24 am

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s