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
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.typeof e.datais a string. I'm unclear how I should be processing this. Why the discrepancy between a stringified JSON object and a basic string? Cheers.messagefrom Redis isn't a string, but when I callconsole.log('received message from redis: ' + message);thentoString()was being called implicitly. I was being lazy and didn't hook up a proper inspector soconsole.logwasn't showing me what I needed to see.console.log('received message from redis: ', message);instead ofconsole.log('received message from redis: ' + message);and you will see the whole object instead of only a.toString()conversion.