epiqu1n
epiqu1n

Reputation: 89

How to check if object is instance of SocketIO.Socket or net.Socket in Node.js?

I am using both generic sockets via the net import as well as sockets from socket.io, and I would like to make a function that works differently depending on which type of socket is passed.

However, the constructor names for both are just "Socket" so I cannot use object.constructor.name, and object instanceof SocketIO.Socket throws an error saying SocketIO is not defined.

Example:

const net = require('net');
const io = require('socket.io')(httpsServer);

function test(socket) {
  if (socket instanceof net.Socket) // Do thing
  else if (socket instanceof SocketIO.Socket) // Do other thing
}

I have also tried using io.Socket, as well as sIO.socket with const sIO = require('socket.io'). Is there any way to make this work by class checking, or do I need to do something like check for a property specific to only one type of socket?

Upvotes: 1

Views: 827

Answers (2)

jfriend00
jfriend00

Reputation: 707158

I would suggest using "duck typing" where you test what properties/methods exist. The phrase duck typing comes from the notion that if it walks and talks like a duck, it must be a duck.

For example to see if a socket is a socket.io socket, you can look for socket.io specific methods and properties that would not be present on a different type of socket such as a net.socket socket.

Assuming this is server-side code, it is easiest to see if it is a socket.io socket and, if not, it must be your other choice:

// look for any one of several socket.io-unique properties
function isSocketIO(socket) {
    return !!(typeof socket.join === "function" || socket.rooms || socket.handshake);
}

Upvotes: 1

spaxxUnited
spaxxUnited

Reputation: 783

You might check for the .constructor of given Object.

socket.constructor === net.Socket

Upvotes: 0

Related Questions