S. Georgian
S. Georgian

Reputation: 143

Increment the counter each time someone connect to server

Guys I have the following code which it supposed to increment a counter each time some one connect to server and post the message in the console but it increments only one time ,can you help me?

'use strict'
//Require express
var express=require('express');
//Trigger express
var app=express();
var counter=0;
//Set up the route URL
app.get('/', function(req, res){
    res.send("<h1>You have connected</h1>");
});

//set up the port
app.listen(3000,function(){

//increment counter

  counter+=1;
  console.log("you have connected " + counter + " times");
})

Upvotes: 1

Views: 3212

Answers (3)

Gireesh Punathil
Gireesh Punathil

Reputation: 1374

  • listen callback is called only once, when the server starts listening.
  • No need of persistence of variable, as long as your server is alive.
  • placing counter inside app.get() block will work only for clients connecting to route '/'.

Ideally, you would need to add a listener to the 'connect' event (express object inherits from HTTP, so the server has this event) of the server, and increment the counter over there:

app.on('connect', function() {
  counter++;
});

Hoe this helps.

Upvotes: 1

Jim Factor
Jim Factor

Reputation: 1535

You need to move your counter to inside the response.

app.get('/', function(req, res){
  counter++;
  res.send("<h1>You have connected "+counter+ " times </h1>");
});

This way whenever the page is loaded it will increment, not just when you boot it up and start listening with app.listen().

Upvotes: 1

DZDomi
DZDomi

Reputation: 1679

Well you have to store the counter variable in some persistant storage like a database or a textfile otherwise it will always be set to zero on each request

Upvotes: 0

Related Questions