jonnyreeves / fetch-readablestream

Compatibility layer for efficient streaming of binary data using WHATWG Streams
MIT License
49 stars 10 forks source link

blob, text & arraybuffer support #3

Closed jimmywarting closed 7 years ago

jimmywarting commented 7 years ago

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 commented 7 years ago

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()?