What is the best method for accessing Blob data in Deno?

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.

Answer №1

If you want to extract the text from a Blob, you can utilize the .text() method.

socket.onmessage = async(event) => {
  const decodedBlob = await event.data.text();
  console.log(decodedBlob);
  const data = JSON.parse(decodedBlob);
};

An alternative approach is to use FileReader, but make sure to include the .onload listener for FileReader.

socket.onmessage = (event) => {
  const reader = new FileReader();
  reader.onload = () => {
    const decodedBlob = reader.result;
    console.log(decodedBlob);
  };
  reader.readAsText(event.data); // make sure to handle data retrieval properly
};

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Error in Electron: Uncaught TypeError - Attempting to assign a value to an undefined property 'title'

Currently, I am in the process of creating some classes for my code using TypeScript, Material UI, React, and Electron. Everything seems to be running smoothly when tested on CodeSandbox. However, when I try to run the code in the Electron environment, all ...

Expanding Angular FormGroup Models with TypeScript

I've developed a foundational model that serves as a base for several other form groups. export class BaseResource { isActive: FormControl; number: FormControl; name: FormControl; type: FormControl; constructor( { ...

Search for specific item within an array of objects

Working on an Angular project, I am attempting to remove an object from an array. To achieve this, I need to filter the array and then update the storage (specifically, capacitor/storage) with the modified array. Here is my function: deleteArticle(id: str ...

Cypress eliminating the "X-CSRFToken" header

There seems to be an issue with the Cypress test runner where it is removing X-CSRFToken from the request header, leading to a 403 Forbidden error. I have compared the headers between a manual run and a Cypress test run, and you can see the difference in t ...

Struggling to successfully deploy an Angular application on Azure

I'm currently in the process of deploying my Angular app to Azure. Utilizing VS Code and the "Azure App Service" extension. I have diligently followed this guide step by step: Upon completing the guide, I was successful in deploying the Angular app ...

Leverage the power of TypeScript by enabling the noImplicitAny flag when working

Currently, I am looking to activate the noImplicitAny flag in my compiler. My main issue lies with utilizing lodash/fp as there are no typings available at this moment. Due to this, the compiler is generating errors due to the absence of a definition file ...

Restrict the parameter type using a type predicate

How can I effectively narrow types based on the value of a single field in TypeScript? It seems that using type predicates may not be working as expected to narrow down the types of other parameters within a type. Is there a way to ensure correct type na ...

Alert from Mongodb when a document is modified

Just picture this scenario: having a MongoDB database with multiple documents and a Node.js server that sends JSON data from the database to the client using Socket.IO. Now, if some external process updates a document that is currently being viewed by the ...

Tips for creating a cookie for an alternate website upon launching a new browser tab

Hey there, I'm facing an issue that I could really use some help with. To give you some context, I'm working on a project using Angular and TypeScript. My goal is to implement single sign-on functionality for multiple websites within one applica ...

Shortcut Express Lane and Socket io

Recently, I configured my socket io connection to send information to the frontend and receive responses from the client. The data is successfully saved as well. However, it seems unnecessary to initialize socket io in the server.js file when its function ...

Yep, identifying InferType optional attributes

Here's an example of a Yup schema I created to fetch entities known as Parcels: export const FindParcelsParamsSchema = Yup.object({ cursor: Yup.number().optional(), pageSize: Yup.number().positive().integer().optional(), }); All fields are option ...

The parameter label is being detected as having an any type, as specified in the Binding element 'label'

Currently, I am referencing an example code snippet from react-hook-form. However, upon implementation, I encounter the following error: (parameter) label: any Binding element 'label' implicitly has an 'any' type.ts(7031) The example c ...

The 'ref' attribute is not found within the 'IntrinsicAttributes' type

I'm currently working on a TypeScript project using React. Although the code is functional, I keep encountering compiler errors with my ref. Here's an example of the code: Firstly, there's a higher-order component that handles errors: expor ...

What is the importance of always catching errors in a Promise?

In my project, I have implemented the @typescript-eslint/no-floating-promises rule. This rule highlights code like this - functionReturningPromise() .then(retVal => doSomething(retVal)); The rule suggests adding a catch block for the Promise. While ...

Having trouble getting useFieldArray to work with Material UI Select component

I am currently working on implementing a dynamic Select field using Material UI and react-hook-form. While the useFieldArray works perfectly with TextField, I am facing issues when trying to use it with Select. What is not functioning properly: The defau ...

Test fails in Jest - component creation test result is undefined

I am currently working on writing a Jest test to verify the creation of a component in Angular. However, when I execute the test, it returns undefined with the following message: OrderDetailsDeliveryTabComponent › should create expect(received).toBeTru ...

Building a Next.js application that supports both Javascript and Typescript

I currently have a Next.js app that is written in Javascript, but I am looking to transition to writing new code in Typescript. To add Typescript to my project, I tried creating a tsconfig.json file at the project root and then ran npm install --save-dev ...

Setting button height dynamically in React Native

I've implemented a button using React Native Elements in my layout. Here's the code snippet: <Button title="Login" buttonStyle={{ backgroundColor: Colour.green }} containerStyle={{ ...

Empty initial value of a number type input element in React using TSX

In the process of developing a react POS app using Typescript, I encountered an issue with calculating change when entering the amount of money received from a buyer. The problem arises when the first value passed to the change calculation logic is empty, ...

invoke a method from a different class within the same component file

I am facing a situation where I have 2 classes within the same component.ts file. One class is responsible for embedding the Doc blot, while the other class serves as the main component class. I need to call a function that resides in the component class f ...