Can't send a Set() object via socket.io in node.js

Viewed 354

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 ?

1 Answers

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]);
Related