H
H
hatealleverything2020-07-28 17:22:52
Express.js
hatealleverything, 2020-07-28 17:22:52

How to implement online in ExpressJS site?

Good afternoon, I decided to make a counter of online users on my website. But I've been sitting for an hour and I don't understand what scheme I need to work on. How can I compare on the server any time if the middleware only works when a request is received.

Throw it all in the middleware

router.use(function(req, res, next) {
    var lasttime = Date.now();
    if (lasttime !== null) {
        timenow = lasttime + 30000
        var usersonline = 0
        usersonline = usersonline + 1

// Здесь я запутался окончательно и так и не понял правильно ли я сравнивал в if

        if (timenow < lasttime) {
            console.log('Пользователь вышел')
        }
    }
    console.log('lasttime  = ' + lasttime)
    console.log('timenow  = ' + timenow)
    console.log('usersonline  = ' + usersonline)
    next()
})


As a result, I did not understand how middleware can do something without a request. It needs to be replaced, but I do not understand what it can be replaced with

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
McBernar, 2020-07-28
@McBernar

Either sockets, or create a temporary user, set a timer for him, with any action on the site, the timer is updated, if it is inactive for more than a minute, we delete it. Obviously, here it is necessary, firstly, to add these users somewhere, and, secondly, to somehow check the lifetime. Better sockets.
In general, there is still an opportunity to access global objects from routes / middles. Will hang in memory until the application is restarted. So, this might be the easiest solution.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question