0

I am using socket.io websockets in nodejs. I am trying to stringify the socket object to be able to save it into my database. Here is what I am doing:

socket.on('open-room', function(arg, callback) {
    var socketStr = JSON.stringify(socket);
}

But I am getting the following error:

TypeError: Converting circular structure to JSON
helloworld
  • 1,002
  • 3
  • 15
  • 27

1 Answers1

3

If you're looking for a general solution on how to convert an object into a JSON string without encountering a circular structure error (usually, you would do this for logging or debugging), check out the S.O. answer Converting Circular Structure to JSON. If it's not important exactly what the output format is, you can use the built in util.inspect(socket).

If you're doing this for any reason other than logging, be aware that a socket.io websocket can't be serialized/deserialized (you won't be able to recreate a working websocket using the database record).

You might have better luck crafting a more specific JSON object containing only the keys you actually care about, and storing that in the database, rather than attempting to stringify the entire object.

Elliot Nelson
  • 11,371
  • 3
  • 30
  • 44