从 Node JS Websocket 接收 <Buffer>

Receiving <Buffer> from Node JS Websocket

我只是想记录来自 websocket 服务器的消息,但我似乎只接收缓冲区数据。以下示例尝试连接到 https://www.piesocket.com/websocket-tester

我做错了什么?

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>

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{"info":"You are using a test api key"}

的十六进制表示

只需将缓冲区转换为字符串:

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"
});