Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Counting the number of hits to my webpage

I have developed a webpage for the internal monitoring of some services of my company. We wish to record the number of hits on the page and display it real time. I have gone through the questions :

Determine how many times webpage has been accessed

How can I count the number of the visitors on my website using JavaScript?

But I can't use google analytics and other such tools. I am hoping it can be done in nodejs. The problem is if I do something like this on nodejs server :

var express = require('express');
var app = express();

var bodyParser = require('body-parser');
var request = require('request');
var cfenv = require('cfenv');
app.use(express.static(__dirname + "/public"));
app.use(bodyParser.json());
var userCount = 0;
app.post('/counterIncrement', function(req, res){
console.log("I received a request to refresh the counter");
userCount = userCount + 1;
res.json({countNum: userCount});
});
var router1 = require('./public/routes/Route1');
router1(app);

var router2 = require('./public/routes/Route2');
router2(app);

var router3 = require('./public/routes/Route3');
router3(app);

var appEnv = cfenv.getAppEnv();

app.listen(appEnv.port, appEnv.bind, function() {

   console.log("server starting on " + appEnv.url); 
});

And everytime someone visits our webpage, we send a request from controller to server to increase the counter. Would this not create a race condition when multiple people access the webpage at the same time? Is there some other way possible?

We had a look at cookies also, but we want to increase the counter even when the same user visits again, and even if thats possible, I am unable to understand how the race condition can be avoided?

like image 354
Nagireddy Hanisha Avatar asked Mar 08 '23 20:03

Nagireddy Hanisha


1 Answers

Assuming You're running a single Node.js process then you can be sure that there'll be no race conditions. Node.js is single threaded and hence all the javascript code is executed synchronously. So each request will run your controller method one at a time.

One drawback of this approach would be that your userCount would be lost as soon as you restart your server as its stored in the process' memory.

However if you're using more than one Node.js process then this method would fail as each Node.js process will maintain its own different userCount. The only fail proof way then would be to use a central database (common to all Node.js process) which already handles race conditions (Most do) and store the count there.

like image 149
Jyotman Singh Avatar answered Mar 27 '23 22:03

Jyotman Singh