Fetch download progress
To track download progress, we can use response.body
property. It’s a ReadableStream
– a special object that provides body chunk-by-chunk, as it comes. Readable streams are described in the Streams API specification.
Unlike response.text()
, response.json()
and other methods, response.body
gives full control over the reading process, and we can count how much is consumed at any moment.
Here’s the sketch of code that reads the response from response.body
:
The result of await reader.read()
call is an object with two properties:
done
–true
when the reading is complete, otherwisefalse
.value
– a typed array of bytes:Uint8Array
.
// instead of response.json() and other methods
const reader = response.body.getReader();
// infinite loop while the body is downloading
while(true) {
// done is true for the last chunk
// value is Uint8Array of the chunk bytes
const {done, value} = await reader.read();
if (done) {
break;
}
console.log(`Received ${value.length} bytes`)
}
Let’s explain that step-by-step:
-
We perform
fetch
as usual, but instead of callingresponse.json()
, we obtain a stream readerresponse.body.getReader()
.Please note, we can’t use both these methods to read the same response: either use a reader or a response method to get the result.
-
Prior to reading, we can figure out the full response length from the
Content-Length
header.It may be absent for cross-origin requests (see chapter Fetch: Cross-Origin Requests) and, well, technically a server doesn’t have to set it. But usually it’s at place.
-
Call
await reader.read()
until it’s done.We gather response chunks in the array
chunks
. That’s important, because after the response is consumed, we won’t be able to “re-read” it usingresponse.json()
or another way (you can try, there’ll be an error). -
At the end, we have
chunks
– an array ofUint8Array
byte chunks. We need to join them into a single result. Unfortunately, there’s no single method that concatenates those, so there’s some code to do that:- We create
chunksAll = new Uint8Array(receivedLength)
– a same-typed array with the combined length. - Then use
.set(chunk, position)
method to copy eachchunk
one after another in it.
- We create
-
We have the result in
chunksAll
. It’s a byte array though, not a string.To create a string, we need to interpret these bytes. The built-in TextDecoder does exactly that. Then we can
JSON.parse
it, if necessary.What if we need binary content instead of a string? That’s even simpler. Replace steps 4 and 5 with a single line that creates a
Blob
from all chunks:let blob = new Blob(chunks);
Author And Source
이 문제에 관하여(Fetch download progress), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://velog.io/@hqillz/Fetch-download-progress저자 귀속: 원작자 정보가 원작자 URL에 포함되어 있으며 저작권은 원작자 소유입니다.
우수한 개발자 콘텐츠 발견에 전념 (Collection and Share based on the CC Protocol.)