Search code examples
javascriptarraysnode.jsobjectws

Understanding the wss.clients object in the ws npm package


I am working with the npm ws library on a Node.js server. I was looking at the documentation and found a way to loop through the clients to, for example, send a message to everyone using the wss.clients object:

const WebSocket = require('ws');
const wss = new WebSocket.server({ port:8080 });
//...
wss.clients.forEach(client => {
  client.send("A message to you!");
});

I initially thought that wss.clients was an array because it let me iterate through it with the array prototype forEach(), but when I tried running wss.clients.find() on it to send a message only to a specific connection, I got an error:

TypeError: wss.clients.find is not a function

I ran console.log(Array.isArray(wss.clients)) it said false. When I tried console.log(wss.clients), I got an object looking like this:

Set { WebSocket { ... } }

So, my question is, how is the wss.clients object able to run the array prototype forEach()? It worked without using Object.keys() or anything. I also tried wss.clients.pop() out of curiosity, and it gave another type error.

What really is wss.clients? An object or an array?


Solution

  • I have discovered (thanks to @waiaan) that the type of wss.clients is a Set. Sets have different methods than arrays, but they are similar.

    The best implementation for Set.prototype.find() would be to define a method like this:

    Set.prototype.find = function(cb) {
        for (const e of this) {
            if (cb(e)) {
                return e;
            }
        }
    }
    

    More about arrays and sets in this article.