Skip to content

Instantly share code, notes, and snippets.

@tj
Created August 31, 2012 05:33
Show Gist options
  • Star 17 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save tj/3549368 to your computer and use it in GitHub Desktop.
Save tj/3549368 to your computer and use it in GitHub Desktop.
users online with redis
var express = require('express');
var redis = require('redis');
var db = redis.createClient();
var app = express();
// track users online (replace UA string with user id)
app.use(function(req, res, next){
var ua = req.headers['user-agent'];
db.zadd('online', Date.now(), ua, next);
});
// fetch the users online in the last minute
app.use(function(req, res, next){
var min = 60 * 1000;
var ago = Date.now() - min;
db.zrevrangebyscore('online', '+inf', ago, function(err, users){
if (err) return next(err);
req.online = users;
next();
});
});
// route
app.get('/', function(req, res){
res.send(req.online.length + ' users online');
});
app.listen(3000);
{
"name": "app",
"version": "0.0.1",
"dependencies": {
"express": "3.x",
"redis": "*"
}
}
@afeld
Copy link

afeld commented Aug 31, 2012

pretty slick

@bobrik
Copy link

bobrik commented Aug 31, 2012

One new user every 50 seconds will make count endlessly increase.

@tj
Copy link
Author

tj commented Aug 31, 2012

guide writeup for this example http://expressjs.com/guide.html#users-online

@tj
Copy link
Author

tj commented Aug 31, 2012

@bobrik good point hahahha, fail

@rubenv
Copy link

rubenv commented Aug 31, 2012

@visionmedia 404 on that guide link (well, the guide is there, the section isn't :-))

@tj
Copy link
Author

tj commented Aug 31, 2012

@rubenv hmm works for me

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment