cannot emit sIo.sockets.clients()


It seems that cannot send the list of connected users, like this:

socket.emit('users', sIo.sockets.clients());

It gives me the following error:

data = JSON.stringify(ev);
TypeError: Converting circular structure to JSON

Apparently it cannot stringify the returned value from sIo.sockets.clients() Any ideas on how to fix this? Thanks in advance.

Problem courtesy of: john smith


Since the problem is a circular reference there no real 'fixing it'. Circular reference means that some object in the structure points to another part of the object, making an infinite loop. What you can do is something like this.

var returnList = [];
var clients = sIo.sockets.clients(); // grab list of clients, assuming its an array
for(var i = 0; i < clients.length; i++) {
  var client = clients[i]; // next client in array

  // push values into return list
    someOther: client.value,
    another: client.thing

// emit cleaned up list
socket.emit('users', returnList);

With this code you can cherry pick the values you want and send only those. This is good for several other reasons. Since this clients list is likely an internal implementation is might also send information about other clients connection.

This is all also pretty speculative as I'm not 100% what libraries you're using, looks like Socket.IO but I cannot find any socket.clients() method.

Solution courtesy of: Morgan ARR Allen


There is currently no discussion for this recipe.

This recipe can be found in it's original form on Stack Over Flow.