New Response from Stream in Microsoft Edge

2020-06-06 19:03发布

问题:

Does someone know of a way to create a new Response from a ReadableStream in Microsoft Edge?

For Chrome, this is quite simple. You can just take a ReadableStream and pass it in the constructor of Response as the first argument. This way you can, for example, create a new Response with say another status code from a network response, without copying the response:

fetch('https://www.baqend.com/')
  .then(res => new Response(res.body, { status: 222 }))
  .then(it => it.text())
  .then(it => console.log('Text prefix ' + it.substr(0,16)))
  .catch(it => console.log('error: ' + it))

While this works perfectly in Chrome, Edge does not support ReadableStream as input for the Response constructor. The only way I get it to work in Edge is when I get the text response first (effectively copying the response and blocking the stream):

fetch('https://www.baqend.com/')
  .then(it => it.text())
  .then(text => new Response(text, { status: 222 }))
  .then(it => it.text())
  .then(it => console.log('Text prefix ' + it.substr(0,16)))
  .catch(it => console.log('error: ' + it))

Does anyone know a way to create a new Response from a Readable Stream in Edge?

PS: I am using Microsoft Edge 42.17115.1.0 (latest developer preview, since I am testing Service Workers)

PPS: The first code does not work in firefox either because firefox does not support getting a RedableStream from Response.body. Edge does expose Response.body though.

回答1:

Try this:

https://www.npmjs.com/package/web-streams-polyfill

var streams = require("web-streams-polyfill");
var readable = new streams.ReadableStream;

// Or, in ES6

import { ReadableStream } from "web-streams-polyfill";