Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Tiny XMLHttpRequest-based requester that returns a ReadableStream-like response. Intentionally very limited. Small.

Notifications You must be signed in to change notification settings

rexxars/xhr-fetch-stream

Repository files navigation

xhr-fetch-stream

Runs a GET-request using XMLHttpRequest against the given URL and provides a subset of a Response object (see Response shape) mimicking what fetch would respond with.

This has an extremely narrow use case: it allows "streaming" the response body using response.body.getReader(), in environments where a native fetch implementation either does not exist, or it does not implement the getReader function. React Native is one such environment.

The hope is for this not to be needed at some point - only bug fixes will be accepted, no new features will (likely) be added here.

Installation

npm install --save xhr-fetch-stream

Usage

import {xhrFetchStream} from 'xhr-fetch-stream'

const abrt = new AbortController()

const response = await xhrFetchStream('https://some.url', {
  // Note: very few properties allowed here
  signal: abrt.signal,
  headers: {some: 'value'},
})

const reader = response.body.getReader()

let done = false
let value

while (!done) {
  ;({done, value} = await reader.read())
  console.log(done ? 'Done!' : `Chunk: ${value}`)
}

Response shape

interface FetchLikeResponse {
  readonly body: {getReader(): ReaderLike} | null
  readonly url: string
  readonly status: number
  readonly redirected: boolean
  readonly headers: {get(name: string): string | null}
}

interface ReaderLike {
  read(): Promise<
    {done: false; value: unknown} | {done: true; value?: undefined}
  >
  cancel(): Promise<void>
}

License

MIT-licensed. See LICENSE.

About

Tiny XMLHttpRequest-based requester that returns a ReadableStream-like response. Intentionally very limited. Small.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published