• 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)
          }
        })
    
  • 相关阅读:
    Python:Pandas的基本操作和使用
    奇技淫巧:绝佳笔记篇-wolai
    Scala:(五) 类、对象、继承、模式匹配和样例类
    tree2List
    java mybatis多层collection嵌套查询
    linux 查看目录下各个文件的大小
    Redisson使用手册
    hutool 定时任务 TimedCache
    清理Docker占用的磁盘空间
    java线程池
  • 原文地址:https://www.cnblogs.com/ybixian/p/12296205.html
Copyright © 2020-2023  润新知