I am building a website with a node.js server.
How would i track logged-in users (clients) and store their id's on the node.js server?
Try this:
var http=require('http');
var connected_users={};
var server=http.createServer(function(req,res){
res.end('hi');
});
server.on('connection',function(socket){
socket.__fd=socket.fd;
connected_users[socket.__fd]=socket.remoteAddress;
console.log(connected_users);
socket.on('close',function(){
delete connected_users[socket.__fd];
console.log(connected_users);
});
});
server.listen(8080);
It prints out to console the array of connected users every time someone connects/disconnects
You can use connect or express NPM modules (express is an extension of connect). Connect (and thus express) has support for cookie-based sessions. Express is a very lightweight and popular framework.
To store users persistently, you can use 'dirty' module. If you need a more advanced store - you can use MongoDB, Riak or even plain old SQL databases (postgreSQL and mySQL), however I suggest to start with dirty or riak to learn the modern approach (namely, key-value stores, in-memory databases, horizontal scalability, document-oriented and other noSQL databases).
If you use express then you should set a session middleware app.use(express.cookieParser()) and app.use(express.session({secret:'some secret'}). By default it stores in memory but you able to use database to store sessions. For more details look in express guide. Is it it?