Skip to content

read() returns number instead of Uint8Array #22

Open
@2ico

Description

@2ico

I am trying to read() a text/event-stream. The backend already works in curl and in a Next.js app.

value returned from reader.read() is a number instead of a Uint8Array, which means the Typescript types are broken.

const fetchMessage = async() => await fetch("http://192.168.1.27:3000/api/chat", {
    "credentials": "include",
    "headers": {
        "User-Agent": "Mozilla/5.0 (X11; Linux x86_64; rv:120.0) Gecko/20100101 Firefox/120.0",
        "Accept": "*/*",
        "Accept-Language": "en-US,en;q=0.5",
        "Content-Type": "text/plain;charset=UTF-8",
        "Sec-Fetch-Dest": "empty",
        "Sec-Fetch-Mode": "cors",
        "Sec-Fetch-Site": "same-origin",
        "Pragma": "no-cache",
        "Cache-Control": "no-cache"
    },
    "body": "{}",
    "method": "POST",
    "mode": "cors"
});

  useEffect(() => {

    function createChunkDecoder() {
      const decoder = new TextDecoder();
        return function(chunk: Uint8Array) {
          console.log(typeof chunk)
          if (!chunk)
            return "";
          return decoder.decode(chunk, { stream: true });
        };
    }

    fetchMessage()
      .then(response => response.body)
      .then(async (stream) => {
        if(!stream){
          return
        }
        const reader = stream.getReader();      
        const decode = createChunkDecoder();

        let streamedResponse = ''

        while(true) {

          const { done, value } = await reader.read();
          if (done) {
            break;
          }

          streamedResponse += decode(value);
          console.log(streamedResponse)

        }
      })
    },[])
   

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions