6

I have a node/ws WebSocket server listening for messages on a Redis backplane, and then forwards it on to any client that is listening:

sub.on("message", function(channel, message) {
    console.log('received message from redis: ' + message);
    console.log('message is type ' + typeof(message));
    var stringified = JSON.stringify(message);
    console.log('stringified is type ' + typeof(stringified));

    wss.clients.forEach(function each(client) {
      client.send(stringified);
    });
});

message is a JSON object. The log output is:

received message from redis: {"temp":81}
message is type object
stringified is type string

On the client, I have:

socket.onmessage = function(e) {
  console.log(e.data)
  ...
};

The log output is:

{"type":"Buffer","data":[123,34,116,101,109,112,34,58,53,52,125]}

Why am I not receiving a string?

If on the server I hardcode:

client.send('foobar');

then the client code will log out:

foobar

4
  • Your whole log output could be a JSON string. Try console.log(typeof e.data) in the client and see if it tells you it is a string. Also, please make the title of your question more meaningful. Commented Dec 26, 2016 at 20:06
  • @jfriend00 Indeed typeof e.data is a string. I'm unclear how I should be processing this. Why the discrepancy between a stringified JSON object and a basic string? Cheers. Commented Dec 26, 2016 at 20:13
  • My issue is message from Redis isn't a string, but when I call console.log('received message from redis: ' + message); then toString() was being called implicitly. I was being lazy and didn't hook up a proper inspector so console.log wasn't showing me what I needed to see. Commented Dec 26, 2016 at 20:55
  • In the future, you can do: console.log('received message from redis: ', message); instead of console.log('received message from redis: ' + message); and you will see the whole object instead of only a .toString() conversion. Commented Dec 26, 2016 at 20:59

1 Answer 1

8

This is due to the fact that any kind of socket-based communication in Node is based on Buffers (more precisely, on Unit8Array, a kind of TypedArray).

You can safely call toString on a Buffer to get a string, or use Streams to make any kind of desired transformations on received data.

Edit: BTW, when you try to console.log a Buffer, it's toString method will be called implicitly.

Sign up to request clarification or add additional context in comments.

1 Comment

Looks like this was user error on my part, but I have no doubt you are indeed correct!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.