Cannot decode Home Assistant WebSocket data with node.js

This is a question specifically related to the Home Assistant system.

I’m trying to look up messages sent and received on WebSocket interfaces between frontend and the backend of Home Assistant. For this purpose I built a very basic HTTP proxy using node.js.

I manage to succesfully record the data sent and received on this WebSocket, but it’s not decodable.

The code:

var http = require('http')
var httpProxy = require('http-proxy');

var proxy = new httpProxy.createProxyServer({
    target: {
        host: 'localhost',
        port: 8123
    }
});

var proxyServer = http.createServer(function (req, res) {
    console.log("Request Received");
    proxy.web(req, res);
});

proxyServer.on('upgrade', function (req, socket, head) {
    console.log("WS Upgrade Request Received");
    proxy.ws(req, socket, head);
    socket.on('data', function(data) {
        console.log('Data sent through WebSocket:', Buffer.from(data).toString());
        console.log('Data sent through WebSocket (JSON):', JSON.stringify(data, true, 2));
        console.log('Data represented as data to string: ', data.toString());
        // exception thrown
        //console.log('Data through JSON.parse(): ', JSON.parse(data));
        // exception thrown
        //console.log('Data represented as buffer: ', JSON.parse(Buffer.from(data)).toString());
    });
});

The problem is that it looks like the data I’m capturing here through the above function is not JSON decoded.

This is an example of output I’m getting:

Data sent through WebSocket: ��F��
Data sent through WebSocket (JSON): {
  "type": "Buffer",
  "data": [
    138,
    128,
    31,
    70,
    156,
    143
  ]
}
Data represented as data to string:  ��F��

According to the Home Assistant WebSocket documentation here: “Each API message is a JSON serialized object containing a type key.”, so the above code shouldn’t show this garbage. Or am I doing something wrong here?

I tried various JSON/Buffer decoding functions as documented above in the socket.on() function, but with no success.