Sails.js. How counting online users?

I’m new with sails.js (node.js). What is the best way to get the number of users online now?

I'm not sure if it's the best way, but one way could be to use a web socket.

On the client side, when someone connects, it could send the username or email, so you can keep a list of online user on the server side.

Then on the web socket disconnect, you remove the user from your list of online user.

There you go, you have the count of online users.

Take a look at http://socket.io/ for more information on how to use web sockets

I hope it helps. :)

Sorry for the late reply but this has come up a couple of times in #sails.js

I don't know if my way is necessarily right, but it works as of 0.9.4 and it's the best way I have found so far:

    // if sails is undefined, get it out of global 
    var sails = global.sails, 
        ws = sails.ws,
        channel = req.param('channel') || '',    // by room, or '' for top level
        current = ws.of(channel).manager.open;   // an array of socket ids 

If you are not using ws, sails.io works too (the structure is slightly different tho.) Call current.length to get the number of connected clients - or you could do something like:

    var status = [];
    for (var x in current) {
        if (ws.of(channel).manager.handshaken.hasOwnProperty(x)) {
            status.push(ws.of(channel).manager.handshaken[x].session.user);
        }
    }
  • to find out who they are. :) HTH

There will be a pool of active sessions that you can use. I'd advise against using socket.io to count users as it doesn't have 100% fallback (it requires flash in some instances)