Managing the accumulation of response chunks in a streaming request with Axios

I have a proxy server that needs to make a request to an external API server to synthesize a voice from some text. According to the API docs, I will first receive a response with headers and then stream binary data, as the response body contains 'Transfer-Encoding: chunked'.

To handle this, I am using responseType: 'stream' in my code:

export const synthesizeVoice = async (contentType: ContentType,
                                      dataForSynthesize: string,
                                      format: string = 'wav16', 
                                      voice:  string = 'Nec_24000') => {
    // Code implementation here...
};

My main issue is that my method returns the file path before receiving the full binary data, resulting in an incomplete audio file on the front end. How can I ensure that I get the complete binary data before sending it, or should I implement streaming requests on the front end as well?

Perhaps there is a better way to approach this problem?

UPDATE: Revised code snippet

axios({
    // Unchanged original code
})
.then(resp => {
    resp.data.pipe(file);

    resp.data.on('end', () => {
        file.close();

        res.set({
            'Content-Type': 'audio/wav16',
        });
        const resFile = fs.createReadStream(file.path).pipe(res);
    });
})
.catch(err => {
    console.log(err.message)
});

Answer №1

If you want to retrieve data effectively, consider using this method.

file.on('data', chunk => {
  console.log(chunk.toString());
});

To execute actions once the data stream concludes, utilize:

file.on('end', chunk => {
  console.log("End");
});

By combining these approaches, you can ensure that you receive the complete file.

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

Unlocking the Power of Custom Fontawesome Icons in Ionic3 ActionSheet

I've been struggling with incorporating custom Fontawesome icons into my ActionSheet buttons in Ionic3. Previously, I was able to use code like this: <i class="fas fa-ad"></i> within the title/text property of the actionsheet button to d ...

When attempting to utilize TypeScript with Storybook, Jest may encounter an error stating, "Incompatible types for property 'id'."

Currently, I'm exploring the use of stories in my unit tests with Jest + RTL to reduce redundancy. However, I've encountered an error stating "Types of property 'id' are incompatible" when passing arguments that are also used in my stor ...

Transform GraphQL data into a JSON format for easier processing

I have developed a JSON api that takes JSON input from Postman and converts it into a graphql request in order to communicate with an external endpoint that exclusively accepts graphql. The conversion process is successful as I am receiving valid graphql r ...

Obtaining data from a Nested Json file in Angular 5

Encountering difficulties retrieving data from nested JSON. Error: 1. <h3>{{sampledata}}</h3> displaying [object Object] 2. <p>{{sampleDataModel.Title}}</p> ERROR TypeError: Cannot read property 'Title' of undefined ...

TypeScript - Minimize redundancy when defining types for a class and its constructor arguments

Here is a class structure I am currently using: class Person { id?: string = uuid(); name: string; constructor(data: Person) { _.merge(this, data); } } The 'uuid' function generates an id and '_' refers to loda ...

The term "containerName" in SymbolInformation is utilized to represent the hierarchy of

In my quest to make the code outline feature work for a custom language, I have made progress in generating symbols and displaying functions in the outline view. However, my next challenge is to display variables under the respective function in the outlin ...

Crafting a model for arrays of objects - a guide to perfection

Why am I experiencing errors in the console when trying to set the API return to a variable? How can this issue be resolved? This is my TypeScript code: public myData = new myDataModel(); getData(){ this.myCoolService.getDataAPI() .subscribe(( ...

"Enhance your development experience with the TypeScript definitions for the Vue 2 plugin

Currently, I am utilizing VSCode alongside TypeScript classes for developing Vue 2 components. You can check out more information at: vuejs/vue-class-component. Within my present project, I make use of plugins like vue-i18n for handling translations of la ...

Encountering a "No overload matches this call" error while using React, Typescript, and d3js

Encountered an error in Typescript while using the scaleLinear() function from d3js. Seeking assistance in resolving this issue. The code is in React and utilizes typescript. Below is the source code: import React, { useRef, useState, useEffect } from &apo ...

Numerous Axios GET calls made by various components

I am facing an issue where I have two different components rendering on the main screen. Both of them make multiple axios.get requests to fetch data. However, upon initial page load, only the last component successfully retrieves the data while the first c ...

Uploading multiple files simultaneously in React

I am facing an issue with my React app where I am trying to upload multiple images using the provided code. The problem arises when console.log(e) displays a Progress Event object with all its values, but my state remains at default values of null, 0, and ...

No elements present in TypeScript's empty set

Question for discussion: Can a type be designed in TypeScript to represent the concept of an empty set? I have experimented with defining one using union, disjoint union, intersection, and other methods... ...

Utilizing variables for Protractor command line parameters

I am struggling to make variables work when passing parameters as a string in my code. Conf.ts params: { testEnvironment: TestEnvironment.Prod, }, env.ts export enum TestEnvironment { Dev = 'dev', QA = 'qa', Prod ...

Creating a read-only DIV using Angular - a step-by-step guide

Is there a simple way to make all clickable elements inside a div read only? For example, in the provided HTML code, these divs act like buttons and I want to disable them from being clicked. Any tips or shortcuts to achieve this? Thank you. #html < ...

What is the best way to create unit tests for a React component using TypeScript?

I recently completed a small React project using TypeScript and decided to have it print numbers of li tags in the browser. During this process, I wanted to write unit tests that would test if the component created the HTML element . However, as someone ...

The element 'Component' is not eligible to be utilized as a JSX component (typed layout)

I encountered a type error while working with the following code snippet: {getLayout(<Component {...pageProps} />)} The error message states that 'Component' cannot be used as a JSX component. This is because its element type 'Compo ...

Loading an external javascript file dynamically within an Angular component

Currently, I'm in the process of developing an Angular application with Angular 4 and CLI. One of my challenges is integrating the SkyScanner search widget into a specific component. For reference, you can check out this Skyscanner Widget Example. T ...

Using TypeScript's .map method to add a new property to an array of objects results in an error stating that the property does not

type Dog = { name: string; furColor: "brown" | "white" }; const addLocation = (animals: Dog[], location: "Italy" | "France") => animals.map((animal) => (animal.location = location)); // animal.location thr ...

Can you apply transparency to a hex color variable in SCSS and then use that variable again?

In my app, I have a set of scss variables that represent colors used throughout the interface. For example: $primary-color: #00755E There are also colors that are variations of this primary color with different opacities. For instance, $primary-color with ...

How to dynamically retrieve values from a const object literal using TypeScript

Currently, I am utilizing a TypeScript library known as ts-proto, which is responsible for generating TypeScript code. The resulting generated code resembles the following: //BasicMessage.ts export interface BasicMessage { id: Long; name: string; } ...