js-compute-runtime icon indicating copy to clipboard operation
js-compute-runtime copied to clipboard

Response.prototype.text() returning empty string in some cases

Open harmony7 opened this issue 2 years ago • 1 comments

Hi all,

I think i’ve found a bug with either Response or ReadableStream, can you check this out when you have a moment?

The following code doesn't work as expected. It should return the same string as the input, but instead it returns an empty string:

  const text = "foo";

  // Create a ReadableStream from string
  const stream1 = new Response(text).body;

  // Read from stream1 using Response.prototype.text();
  const textFromStream1 = await new Response(stream1).text();

  // textFromStream1 should be 'foo', but it's ''

I've put a repro of this up in a fiddle https://fiddle.fastly.dev/fiddle/750711db This happens for me on the newest version of js-compute-runtime: 3.8.2

harmony7 avatar Feb 07 '24 05:02 harmony7

Something to note is that if I instead use a reader like this, I get the right result (so I'm currently using this as a workaround):

  const text = "foo";

  // Create a ReadableStream from string
  const stream2 = new Response(text).body;

  // Use a reader to read from stream2
  const stream2Reader = stream2.getReader();
  let textFromStream2 = '';
  const decoder = new TextDecoder();
  while(true) {
    const { done, value } = await stream2Reader.read();
    if (done) {
      break;
    }
    textFromStream2 += decoder.decode(value);
  }

  // textFromStream2 correctly contains 'foo'

harmony7 avatar Feb 08 '24 06:02 harmony7