I have a Node, Express, and Websockets
chat app. The usernames of the users currently in the chatroom is stored to Redis
. From the redis-cli
when I type in SMEMBERS 'onlineUsers'
, I get back a list of all the users currently in the room:
127.0.0.1:6379> smembers 'onlineUsers'
1) "jackson"
2) "bubba yump"
3) "dog"
4) "rumba"
5) "buba"
In my main application javascript
file I have a method to get the current users so I can display them on the page:
var showCurrentUsers = function(){
$('#list_of_users').empty();
$.getJSON('getUsers', function(data){
console.log(data)
for (var i in data){
$('#list_of_users').append("<li> User: "+data[i]+"</li>")
}
});
}
In my Node
server file I have the matching route but db.smembers
keeps returning true
instead of a list of the users.
app.get('/getUsers', function(req,res){
res.send(getOnlineUsers());
});
// REDIS DATA
var getOnlineUsers = function(){
return db.smembers("onlineUsers")
}
and here is where the username is originally posted to the database:
client.on("setUsername", function(user){
pub.publish("chatting","A new user in connected:" + user);
db.sadd("onlineUsers",user);
}
);
I know that the usernames are correctly posting to the database, and I can access them from the redis-cli
, but I'm not sure why my JSON call is returning true
instead of the list.
(I'm assuming you're using https://github.com/mranney/node_redis)
The node redis client is async. You can treat it as sync for writes and deletes, but to read from the db you need to use a callback.
app.get('/getUsers', function(req, res, next){
getOnlineUsers(function (err, onlineUsers) {
if (err) {
return next(err);
}
res.send(onlineUsers);
});
});
// REDIS DATA
var getOnlineUsers = function(cb){
return db.smembers("onlineUsers", cb);
}