使用节点获取计算下载百分比的正确方法

Correct way to calculate download percentage with node-fetch

我有以下方法 installFile 从 S3 下载文件到磁盘。该代码完美运行。我删除了一堆不相关的代码,只包含了我正在努力处理的部分。

我想要做的是 console.log 此文件在下载时的下载百分比。

这里是代码的选择,特别是我使用 res.body.read().

访问接收到的字节的地方
... other imports etc   
import fetch from 'node-fetch'


export const installFile = async (file: FileReference): Promise<FileInstalledEvent> => {
  const s3Link = await getDownloadLink(file.id as number)
  const res = await fetch(s3Link)

  const contentLengthHeader = res.headers.get('Content-Length')
  const resourceSize = parseInt(contentLengthHeader, 10)

  return new Promise((resolve, reject) => {

    /* Keep track of download progress */
    res.body.on('readable', () => {
      let chunk
      let recievedLength: number = 0
      let downloadProgressAsPercentage: number = 0
      
      while (null !== (chunk = res.body.read())) {
        console.log(`Received ${chunk.length} bytes of data.`)
        recievedLength += chunk.length
        console.log("recieved", recievedLength, "of", resourceSize, "bytes")

        downloadProgressAsPercentage = recievedLength / resourceSize * 100
        console.log("Download percentage:", downloadProgressAsPercentage, "%")

      }
    })
... after this I go on to handle the file etc etc (which works fine)

文件下载正常,但控制台日志看起来是这样的。这些数字真的让我感到困惑:)

Received 16360 bytes of data.
recieved 16360 of 4874349 bytes
Download percentage: 0.3356345637130209 %
Received 16360 bytes of data.
recieved 16360 of 4874349 bytes
Download percentage: 0.3356345637130209 %
Received 9050 bytes of data.
recieved 9050 of 4874349 bytes
Download percentage: 0.18566581916887773 %
download finished

为什么我最后没有达到 100%?

您可以使用 Math.floor() 方法。

Math.floor((loaded / total) * 100)