Node.js中下載文件, 獲取下載進度


原文:https://www.jianshu.com/p/36cc5042ef12

/**
 * 文件下載
 * @param {*} url 下載地址
 * @param {*} dest 文件保存的路徑,如:D:/download/app/ybx1.apk
 * @param {*} cb 回調函數參數1為區別哪個加試,如:'download'下載結束,'data'下載進度,'finish'文件寫入結束
 */
const downloadFile = (url, dest, cb = () =>{}) => {
  // 確保dest路徑存在
  const file = fs.createWriteStream(dest)
  const urlImage = 'https://seven-actions.oss-cn-shenzhen.aliyuncs.com/sa_rail_work_sheet_resource/b517de9a-2abc-11ea-8e3c-0242ac140007.mp4'
  
  https.get(urlImage, (res) => {
    if (res.statusCode !== 200) {
      cb(response.statusCode)
      return
    }

    // 進度
    const len = parseInt(res.headers['content-length']) // 文件總長度
    let cur = 0
    const total = (len / 1048576).toFixed(2) // 轉為M 1048576 - bytes in  1Megabyte
    res.on('data', function (chunk) {
      cur += chunk.length
      const progress = (100.0 * cur / len).toFixed(2) // 當前進度
      const currProgress = (cur / 1048576).toFixed(2) // 當前了多少
      cb('data', progress, currProgress, total)
    })

    res.on('end', () => {
      // console.log('下載結束')
      cb('download')
    })

    // 超時,結束等
    file.on('finish', () => {
      // console.log('文件寫入結束')
      file.close(cb('finish'))
    }).on('error', (err) => {
      fs.unlink(dest)
      if (cb) cb('error', err.message)
    })
    res.pipe(file)
  })
}

調用

    downloadFile(download_url, savaFilePath + `${data.package_version}.apk`, (state, pro, currPro, total) => {
      if (state == 'data') {
        // 下載進度
        console.log(pro, currPro, total)
      }
    })


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM