Home > Back-end >  Receiving <Buffer> from Node JS Websocket
Receiving <Buffer> from Node JS Websocket

Time:01-16

I'm simply trying to log messages from a websocket server but I seem to only receive Buffer data. The below example is trying to connect to https://www.piesocket.com/websocket-tester

What am I doing wrong?

import WebSocket from 'ws'
const demoStreamer = new WebSocket('wss://demo.piesocket.com/v3/channel_1? 
api_key=oCdCMcMPQpbvNjUIzqtvF1d2X2okWpDQj4AwARJuAgtjhzKxVEjQU6IdCjwm&notify_self')

demoStreamer.on('message', (data) => {
  console.log(data);
});

// OUTPUT: 
// <Buffer 7b 22 69 6e 66 6f 22 3a 22 59 6f 75 20 61 72 65 20 75 73 69 6e 67 20 61 20 74 65 73 
// 74 20 61 70 69 20 6b 65 79 22 7d>
// <Buffer 54 65 73 74 20 6d 65 73 73 61 67 65>
// <Buffer 54 65 73 74 20 6d 65 73 73 61 67 65>

CodePudding user response:

7b 22 69 6e 66 6f 22 3a 22 59 6f 75 20 61 72 65 20 75 73 69 6e 67 20 61 20 74 65 73 74 20 61 70 69 20 6b 65 79 22 7d is a hexadecimal representation of {"info":"You are using a test api key"}

Just convert the buffer to string:

demoStreamer.on('message', (data) => {
  console.log(data.toString()); // "{\"info\":\"You are using a test api key\"}"
  // Retrieve the info message:
  console.log(JSON.parse(data).info); // "You are using a test api key"
});
  •  Tags:  
  • Related