Hit/Site Counter using NodeJs

  1. var http = require('http');  
  2. var hitcounter = 0;  
  3. http.createServer(function(request,response){  
  4.     hitcounter += 1;  
  5.     response.writeHead(200,{'Content-Type':'text/plain'});  
  6.     response.write('My Site Counter Visit: ' + hitcounter);  
  7.     response.end();  
  8. }).listen(8080);

1. The first line is just getting the 'http' module and storing it into some variable.

2. Next statement is just a counter variable starts with '0', so that with ever new request is starts increasing.
 
3. Next we are creating our http server by calling 'createServer' method.
 
4. In between the code logic is written for every new request.
 
5. At last we are listening to port 8080 by using 'listen' method.
 
 
Just 8 lines of code... This is just beginning.. 
Same code can be reduced to just 3-4 lines... :)