Currently, I am attempting to read from a websocket within Deno. Below is the code snippet (please note that you will require an API key from AISstream for it to function properly)
/**
* URL used by the API; this might change if the version changes or at any time, since it's experimental
*/
const AIS_API_URL = "wss://stream.aisstream.io/v0/stream";
export const defaultBoundingBox = [
[
[-90, -180],
[90, 180],
],
];
let socket = null;
// Creates a Deno websocket client and subscribes to the AIS API
export function createSocket(apiKey, boundingBoxes = defaultBoundingBox) {
if (socket) {
return socket;
}
socket = new WebSocket(AIS_API_URL);
socket.onopen = () => {
console.log("Socket connected");
socket.send(
JSON.stringify({
apiKey,
boundingBoxes,
})
);
};
socket.onmessage = (event) => {
const reader = new FileReader();
console.log(event);
const decodedBlob = reader.readAsText(event.data);
console.log(decodedBlob);
};
socket.onclose = () => {
console.log("Socket closed");
};
return socket;
}
The issue lies within the on message
section. Event messages are being received successfully. However, the data
is in a Blob
format. I have attempted to decode it using methods like TextDecoder
and readAsText
, but unfortunately, it returns undefined
.
When using JavaScript here: event.data
is returned as a string, which can then be parsed into JSON. Nonetheless, this particular problem stumps me.