简体   繁体   English

如何限制来自 fetch API 的流以节省带宽?

[英]How can I limit the stream from fetch API to save bandwidth?

How do I get the fetch API to cut off the stream after a few hundred bytes?如何让 fetch API 在几百字节后切断流? I only need the meta description from the top of the page, and the rest of the page is upwards of 500k我只需要页面顶部的元描述,页面的其余部分超过 500k

Check if the website has a feature that allows you to send a flag that tells them to only send the meta description.检查网站是否具有允许您发送标志的功能,告诉他们只发送元描述。

If it doesn't, then your machine is going to receive the data no matter what.如果没有,那么您的机器无论如何都会接收数据。 If you want to save time reading the whole response, you can just read until you have all the meta information, then stop reading and discard the rest.如果你想节省阅读整个响应的时间,你可以阅读直到你拥有所有的元信息,然后停止阅读并丢弃其余的。 This will just save you some I/O time, not bandwidth.这只会为您节省一些 I/O 时间,而不是带宽。

You can use the Response.body stream to read the received data bit by bit and use an AbortSignal to cancel the request when you have received enough data.您可以使用Response.body流逐位读取接收到的数据,并在收到足够的数据时使用AbortSignal取消请求。

Note that you cannot control how much data you will receive in each chunk, so you might receive more than needed, but I would assume that with 500 KB, the data will arrive in multiple chunks, so by canceling you will save some data.请注意,您无法控制在每个块中将收到多少数据,因此您可能会收到比需要更多的数据,但我假设使用 500 KB,数据将以多个块的形式到达,因此通过取消您将节省一些数据。

Here is some example code that will abort as soon as it has received at least 10 KB:以下是一些示例代码,一旦收到至少 10 KB 就会中止:

const LIMIT = 10000;
const abort = new AbortController();
const res = await fetch(url, {
    signal: abort.signal
});

let bodySoFar = '';
const reader = res.body.pipeThrough(new TextDecoderStream()).getReader();
while (true) { // eslint-disable-line no-constant-condition
    const { done, value } = await reader.read();
    if (done) {
        break;
    }
    bodySoFar += value;
    if (bodySoFar.length > LIMIT) {
        abort.abort();
        break;
    }
}

Note that TextDecoderStream does not have good browser support yet.请注意, TextDecoderStream还没有很好的浏览器支持。 As a workaround, you can collect the data in an Uint8Array instead.作为一种解决方法,您可以改为Uint8Array中收集数据

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM