6

I'm trying to send a Set() object via socket.io from node.js server. But from client side I'm getting an empty object.

//server side
var set=new Set([1,2,3]);
socket.emit('set', set);
console.log(set); //Set(3) {1,2,3}
//client side
socket.on('set',function(set){
  console.log(set); //{}
});

Why is that ?

Christian Baumann
  • 3,188
  • 3
  • 20
  • 37
Chamod
  • 587
  • 2
  • 6
  • 17

1 Answers1

6

From the docs:

All serializable datastructures are supported, including Buffer.

Set is not serializable (try doing JSON.stringify(new Set([1, 2, 3])). However, Array is serializable and you can convert a set into an array with a spread operator:

const s = new Set([1,2,3]);
socket.emit('set', [...s]);
gurisko
  • 1,172
  • 8
  • 14
  • Thank you very much for the answer. Are there any performance difference between [...s] & Array.from(s) – Chamod Sep 30 '20 at 11:40
  • 1
    @Chamod It all depends on your environment - are you running natively or are you transpiling into ES5? Also, in most scenarios differences are going to be negligible. Have a look at [Array.from() vs spread syntax](https://stackoverflow.com/questions/40548213/array-from-vs-spread-syntax) – gurisko Sep 30 '20 at 11:46