Skip to content

[feature] Support ReadableStream response body #34

@dankeboy36

Description

@dankeboy36

I propose adding an API for a streaming response type. The body could be a type of ReadableStream, similar to Response.body.

This feature would be handy when VSIX downloads files. It allows for direct piping of data into a write stream without the need to store it in memory.

Implementing this could also enable progress tracking in client code. Clients using xhr can receive the response without waiting and obtain the 'content-length' from the headers. They can then process the incoming chunks using a reader and calculate the download percentage for the withProgress VSIX window API.

API Proposal

api.d.ts:

export interface StreamXHROptions extends XHROptions {
    responseType: 'stream';
}
export type StreamXHRResponse = Omit<XHRResponse, 'body'> & { readonly body: Response['body'] };

export interface XHRRequest {
    (options: XHROptions): Promise<XHRResponse>;
    (options: StreamXHROptions): Promise<StreamXHRResponse>; // <-- new API
}

Client Examples

node/client.ts:

const response = await xhr({ url: getUrl(server), responseType: 'stream' });
const readable = Readable.fromWeb(response.body);

let data = '';
for await (const chunk of readable) {
    data += chunk;
}

browser/client.ts:

const response = await xhr({ url: getUrl(server), responseType: 'stream' });

let data = '';
const reader = response.body.getReader();
let done: boolean, value: Uint8Array | undefined;

while (!done) {
    ({ done, value } = await reader.read());
    if (value) {
        data += new TextDecoder().decode(value);
    }
}

Overall, I believe this feature could be very useful and is feasible to implement. I will fork it and implement it in my repository, but if the maintainers think it could benefit the main repository, I would be happy to open a pull request.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions