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)
      }
    })

猜你喜欢

转载自www.cnblogs.com/ybixian/p/12296205.html