You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: files/en-us/web/api/fetch_api/using_fetch/index.md
+63-8Lines changed: 63 additions & 8 deletions
Original file line number
Diff line number
Diff line change
@@ -397,17 +397,67 @@ The method will throw an exception if the response body is not in the appropriat
397
397
398
398
Request and response bodies are actually {{domxref("ReadableStream")}} objects, and whenever you read them, you're streaming the content. This is good for memory efficiency, because the browser doesn't have to buffer the entire response in memory before the caller retrieves it using a method like `json()`.
399
399
400
-
This also means that the caller can create a reader for the stream using {{domxref("ReadableStream.getReader()")}}, and then process the content as it arrives, without having to wait for the entire response body to arrive.
400
+
This also means that the caller can process the content incrementally as it is received.
401
401
402
-
In the example below, we fetch a text resource and process it line by line:
402
+
For example, consider a `GET` request that fetches a large text file and processes it in some way, or displays it to the user:
In this example, we {{jsxref("Statements/for-await...of", "iterate asynchronously", "", "nocode")}} over the stream, processing each chunk as it arrives.
447
+
448
+
Note that when you access the body directly like this, you get the raw bytes of the response and must transform it yourself. In this case we call {{domxref("ReadableStream.pipeThrough()")}} to pipe the response through a {{domxref("TextDecoderStream")}}, which decodes the UTF-8-encoded body data as text.
449
+
450
+
### Processing a text file line by line
451
+
452
+
In the example below, we fetch a text resource and process it line by line, using a regular expression to look for line endings. For simplicity, we assume the text is UTF-8, and don't handle fetch errors:
0 commit comments