Question:
How can you read a Blob in Deno in TypeScript?

Problem

I'm trying to read from a websocket in Deno. Here's the code (you'll need an API key from AISstream to make it work)


AISstream to make it work)

/**

 * 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 problem is in the message. Messages/events are received successfully. However, the data is in a Blob. I have tried to decode it using TextDecoder, as well as readAsText. However, this returns undefined.


Using JS is no problem here: event.data is returned as a string, which can then be parsed to JSON. However, I can't figure this one out.


Solution

In order to read the contents of a Blob as text, you could use >.text() method.


socket.onmessage = async(event) => {

  const decodedBlob = await event.data.text();

  console.log(decodedBlob);

  const data = JSON.parse(decodedBlob);

};


You could also use FileReader as you were trying, but you missed the .onload listener of FileReader


socket.onmessage = (event) => {

  const reader = new FileReader();

  reader.onload = () => {

    const decodedBlob = reader.result;

    console.log(decodedBlob);

  };

  reader.readAsText(event.data); // does not return the data

};


Suggested blogs:

>Why Typescript does not allow a union type in an array?

>Narrow SomeType vs SomeType[]

>Create a function that convert a dynamic Json to a formula in Typescript

>How to destroy a custom object within the use Effect hook in TypeScript?

>How to type the values of an object into a spreadsheet in TypeScript?

>Type key of record in a self-referential manner in TypeScript?

>How to get the last cell with data for a given column in TypeScript?

>Ignore requests by interceptors based on request content in TypeScript?

>Create data with Typescript Sequelize model without passing in an id?

>How to delete duplicate names from Array in Typescript?


Nisha Patel

Nisha Patel

Submit
0 Answers