How to get the "end" event from http with fetch API

Asked

Viewed 79 times

0

I want to use the API fetch instead of the http(Node) module. However, I’m not getting the end of the request.

var req = http.request(options, res => {
    res.setEncoding("utf8");
    res.on('data', () => {
      //como entro nesse trecho com o fetch ???
    });
    res.on("end", () => {
      //como entro nesse trecho com o fetch ???
    });
  });

I want to catch these "events" with the fetch ???

fetch(_end, options)
                .then(res => {
                    res.on('data', () => { 
                      //Não exite esse res.on utilizando o fetch
                    });
                    res.on("end", () => {
                        //Não exite esse res.on utilizando o fetch.
                    });
                })
                .catch(err => {
                    ...
                });

Can anyone give me any hint on how to do this using the fetch API.

  • Want to use fetch in browser or Node?

  • fetch on Bowser

  • use in Chrome browser

1 answer

1


The fetch and the request has different Apis. fetch returns a file and state control is done by API of the Promise with the .then, .catch and .finally; while the request works with events.

So you can choose to run code on:

  • then: called when all goes well
  • catch: called when something goes wrong (it should always be set to the code not stop if there is an error)
  • finally: called whether Promise has been resolved or rejected

Example:

fetch('https://jsonplaceholder.typicode.com/todos/')
  .then(async response => {
    const dados = await response.json();
    console.log('Tudo correu bem!');
    console.log('Qtd de dados:', dados.length);
  })
  .catch(err => console.log('Houve um erro!', err))
  .finally(() => console.log('The end!...'));

  • Just one question: If Response returns a file. And the.length data is done as you did. This will be the file size value ?

  • This data.length is the size in bytes ?

  • @frontend no, in this case it would be the amount of characters in json. To know the number of Bites you would have to convert to a binary, I’m not quite sure how to measure that.

  • How do I know the size of the Response return in bytes ?

  • Does that solve:

  • const Reader = res.body.getReader(); Let bytesReceived = 0; while (true) { const result = await Reader.read(); if (result.done) { console.log('Fetch complete'); break; } bytesReceived += result.value.length; console.log('Received', bytesReceived, 'bytes of data so far'); }

  • @frontend is possible. Avoid while(true), you can use instead while(!result.done).

  • Thank you very much :D

  • will return the size of a correct file ? fetch(url) . then(Response => Response.blob()) . then(data => console.log('Download ended. Bytes downloaded:', data.size))

Show 4 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.