sending a javascript object through websockets with faye


Hi all I'm trying to send a javascript object through websockets:

the faye-websockets documentation says:

send(message) accepts either a String or a Buffer and sends a text or binary message over the connection to the other peer.

server side I'm using node and faye.

var WebSocket = require('faye-websocket');
var http = require('http');

var server = http.createServer();
server.addListener('upgrade', function(request, socket, head) {
    var ws = new WebSocket(request, socket, head);
    ws.send({topic:'handshake', data:'sdf487rgiuh7'});

client side:

    var ws = new WebSocket('ws://localhost:8000');
    ws.onmessage = function(e) {
        console.log(; //prints [Object object] string and not the object

what is my error? Thanks

3/12/2015 4:29:02 PM

Accepted Answer

WebSockets support sending and receiving: strings, typed arrays (ArrayBuffer) and Blobs. Javascript objects must be serialized to one of the above types before sending.

To send an object as a string you can use the builtin JSON support:


To send an object as a typed array you can use a javascript BSON library such as this one:


When you receive a WebSocket message you will need to deserialize it.

To deserialize a JSON string from a WebSocket message:

ws.onmessage = function (e) {
    var object = JSON.parse(;

If you are using binary messages over WebSocket, then first you should set the binaryType attribute in order to receive all binary messages as typed arrays:

ws.binaryType = "arraybuffer";

Then the deserialization will look like this:

ws.onmessage = function (e) {
    var object = BSON.deserialize(;

Here is a blog post about using BSON in Javascript;

10/23/2012 3:39:31 PM


const bson = new BSON();
ws.binaryType = 'arraybuffer';

ws.onmessage = function(event) {


 const data = bson.serialize({ ... });

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow