This video tutorial is a rapid application development to illustrate HTTP Server(request/response) using Node.js
In this video, we use HTTP Server(request/response): Node.js code and work on it to develop a simple counter application.
Using this application, we can know how many visits have been made since the last server down time!
For explanation of all the keywords and working, please visit HTTP Server(request/response): Node.js
HTTP Server
count.js
var http = require('http');
var visits = 0;
http.createServer( function(request, response) {
console.log('New Connection');
visits++;
response.writeHead(200, { 'Content-Type':'text/plain' } );
response.write('Hello\n');
response.write('We have had '+visits+' visits');
response.end();
}).listen(8080);
console.log('Server Started..');
Here we take a variable called visits and initialize it to 0.
Once there is a new connection request, we increment it’s value by 1.
Since there is also request from favicon, practically, there’ll be 2 requests simultaneously: hence the counter increments by 2 for each new connection request.
using write method, we print the number of visits.
HTTP Server(request/response) Counter Application: Node.js
Output:
Hello
We have had 3 visits
Note:
Once you stop the server or whenever there is down time in the server, the counter is reinitialized once the server is restarted.
Make use of Database to store the counter value, if you need it inspite of server downtime or restarts.