javascript-tutorial / javascript-tutorial/zh.javascript.info

网络请求-3-fetch 下载进度 勘误

Open
#1,246 0 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Dominant language
HTML
Stars
10.8k
Forks
1.2k
PR merge metrics
No merged PRs in 30d

Description

原文链接:https://zh.javascript.info/fetch-progress

在Content-Encoding指定了某种压缩方式时,fetch提供的getReader中读取到的是解压缩*后*的二进制流,而Content-Length所指示的是解压缩前的请求体大小。

在绝大多数场景,浏览器自动指示Accept-Encoding的情况下,不能直接使用Content-Length作为完整报文长度进行进度计算,而应当使用其它方式/响应头告知客户端完整的报文长度。

原文中示例代码如下:

```js
// Step 1:启动 fetch,并获得一个 reader
let response = await fetch('https://api.github.com/repos/javascript-tutorial/en.javascript.info/commits?per_page=100');

const reader = response.body.getReader();

// Step 2:获得总长度(length)
const contentLength = +response.headers.get('Content-Length');

// Step 3:读取数据
let receivedLength = 0; // 当前接收到了这么多字节
let chunks = []; // 接收到的二进制块的数组(包括 body)
while(true) {
const {done, value} = await reader.read();

if (done) {
break;
}

chunks.push(value);
receivedLength += value.length;

console.log(`Received ${receivedLength} of ${contentLength}`)
}

// 以下略
```

Contributor guide

No contributing guide indexed for this repository

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start with the fetch progress article at https://zh.javascript.info/fetch-progress and review the example using response.body.getReader(), Content-Length, and receivedLength. Correct the explanation or example so it accounts for compressed responses, and confirm that the documented progress calculation matches the byte stream returned by fetch.

Written by the indexing model from the issue text.

Assessment

Tech stack
javascript
Domain
documentation
Issue type
Documentation
Difficulty
2/5
Estimated time
1-3 hours
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
45/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.