Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

blob, text & arraybuffer support #3

Closed
jimmywarting opened this issue Oct 14, 2016 · 1 comment
Closed

blob, text & arraybuffer support #3

jimmywarting opened this issue Oct 14, 2016 · 1 comment

Comments

@jimmywarting
Copy link

jimmywarting commented Oct 14, 2016

It doesn't take much to make turn a stream into a arraybuffer, text or a blob... consider adding? for a complete api...

  const read = (blob, readAs) => {
    return new Promise((resolve, reject) => {
      const reader = new FileReader()
      reader.onload  = () => resolve(reader.result)
      reader.onerror = () => reject(reader.error)
      reader[readAs](blob)
    })
  }

  const readBlobAsArrayBuffer = blob => read(blob, 'readAsArrayBuffer')
  const readBlobAsText        = blob => read(blob, 'readAsText')
  const readStreamAsBlob      = body => {
    const reader = body.getReader()
    const chunks = []
    const pump = () => {
      return reader.read().then(res => {
        if (res.done) {
          chunks.push(res.value)
          return pump()
        }
      })
    }

    return pump().then(() => new Blob(chunks))
  }

  // 
  // For Response class
  // 
  blob() {
    this.bodyUsed = true
    return readStreamAsBlob(this.body)
  }

  text() {
    return this.blob().then(readBlobAsText)
  }

  arrayBuffer() {
    return this.blob().then(readBlobAsArrayBuffer)
  }
@jonnyreeves
Copy link
Owner

This implementation is not aiming to be a complete polyfill for fetch, it's just aiming to provide a stream-based API for fetching binary data in the browser. As for adding text() and arrayBuffer methods; could the consumer not just make use of .pipeTo()?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants