Sometimes, we want to retrieve data from a JavaScript ReadableStream object.
In this article, we’ll look at how to retrieve data from a JavaScript ReadableStream object.
Retrieve Data from a JavaScript ReadableStream Object
To retrieve data from a JavaScript ReadableStream object, we need to call a conversion method to convert the ReadableStream to the actual data we can use.
For instance, we write:
(async () => {
const response = await fetch("https://httpbin.org/ip");
const body = await response.json();
console.log(body)
})()
to make a GET request to https://httpbin.org/ip with fetch
.
fetch
returns a promise that resolves to a ReadableStream object which we assigned to response
.
Then to convert that to the response data by calling the json
method since the response data is serialized into JSON format.
json
also returns a promise so we have to use await
on that and assign the resolved value to body
.
Therefore, body
should have the data from the ReadableStream object.
Conclusion
To retrieve data from a JavaScript ReadableStream object, we need to call a conversion method to convert the ReadableStream to the actual data we can use.