Home > DeveloperSection > Beginner > Counter Example in Node.js

Counter Example in Node.js

Node.JS Node JS 
0 Comment(s)
 2548  View(s)
Rate this:

Counter Example in Node.js

In this article, I’m explaining the simple example of node.js that count the number of visits in server.

In this article, I’m explaining an example to count number of visit on the server. Let’s create the example by the following code:

First of all choose location where you create the program. Here, I select the location C:\node and create a file that is counter.js.

var http = require('http');


var userCount = 0;

http.createServer(function (request, response) {

    console.log('New connection');



    response.writeHead(200, {'Content-Type': 'text/plain'});


    response.write('We have had '+userCount+' visits!\n');




console.log('Server started run at the http://localhost:8000');


At this example we create a server at the port of 3000 and every time count the server creation by the usercount variabale. When you run the program first time a message generate Server started run at the http://localhost:8000. Let’s run it by the command prompt.

Counter Example in Node.js

We have to need to run on the browser at the http//:localhost:3000/. Let’s show that it into browser:

Counter Example in Node.js

We see that when the program first time run then give the Message We have had 1 visits! And also need to check at the console:

Counter Example in Node.js

Here a new message to New Connection that we tell that new connection created. In the browser when you refresh the page every time give the message and count the number visits. We need to check that here, I refresh the page 4 times then the number of visits is 5 times. Let’s check:

Counter Example in Node.js

Here give the message we have had 5 visits! And we turn to the console and look that what happen in console:

Counter Example in Node.js

Here four New Connection message generate that every time create server method call.

I hope that this article is helpful for understanding server refresh mechanisms for you. Thanks!


Don't want to miss updates? Please click the below button!

Follow MindStick