ws.send method should support objects too

Created on 10 May 2017  路  7Comments  路  Source: websockets/ws

This code works:

ws.send(JSON.stringify({test: 'test'}));

This doesn;t:

ws.send({test: 'test'});

I propose an enhancement in Sender.js to allow or convert objects automatically.

Most helpful comment

It is great that I find this issue, though. I couldn't figure out what I was doing wrong... Thanks for posting @ZaDarkSide !

All 7 comments

Sending JSON would make no sense as it would not be decoded automatically on a WebSocket client.

You are right, but instead of throwing an error like this one:

"TypeError: First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object."

Maybe instead the error message should be improved at least something like:
"If you are trying to send a object please serialize it first with your method of choice, JSON, BSON, etc."

Related with https://github.com/HenningM/express-ws/issues/72

That error is thrown by Node.js when you try to make a buffer from an object.

Buffer.from({ test: 'test' });

The WebSocket protocol only works with text and binary data so anything regarding SerDes should not be handled by this lib.

Yes I understand, but in Sender.js there is already some code that does conversion from ArrayBuffer to Buffer, why not add conversion from Object to Buffer also?

That's already binary data, we have to convert to it Buffer because that's the "type" required by Node.js API and to know the length in bytes of a string.

Okay, it's a minor issue for me, closing this.

It is great that I find this issue, though. I couldn't figure out what I was doing wrong... Thanks for posting @ZaDarkSide !

Was this page helpful?
0 / 5 - 0 ratings

Related issues

robertmylne picture robertmylne  路  3Comments

NodePing picture NodePing  路  5Comments

bartosz-m picture bartosz-m  路  3Comments

cmnstmntmn picture cmnstmntmn  路  4Comments

dcflow picture dcflow  路  4Comments