首页 > 编程语言 >NodeJS下载文件并显示下载进度

NodeJS下载文件并显示下载进度

时间:2022-11-24 10:38:20浏览次数:36  
标签:function const NodeJS url 进度 https targetUrl progress 下载

const fs = require('fs');
const request = require("request")
const progress = require('progress-stream')
const https = require("https")
const http = require("http")

/* 下载文件
		@param url 文件地址
		@param targetUrl 存储地址
	 */
async function downloadUrlFile(url, targetUrl) {
    let stream = fs.createWriteStream(targetUrl)
    let p = await setDownloadProgress(url)
    return new Promise(function (resolve, reject) {
        request(url).pipe(p).pipe(stream).on('close', function () {
            winston.info(targetUrl + '下载完毕');
            resolve(targetUrl)
        });
    })
}
/* 获取文件大小 */
async function getUrlFileSize(url) {
    return new Promise(r => {
        let h = {http, https}
        let isHttps = url.indexOf("https") != -1
        h[isHttps ? "https" : "http"].get(url, {
            rejectUnauthorized: false
        }, (res) => {
            r(res.headers['content-length'])
        })
    })
}

/* 设置下载进度 */
async function setDownloadProgress(url) {
    let p = progress({
        length: await getUrlFileSize(url),
        time: 500
    })
    p.on('progress', progress => {
        console.log("下载进度:", progress.percentage)
    });
    return p
}

标签:function,const,NodeJS,url,进度,https,targetUrl,progress,下载
From: https://www.cnblogs.com/zhangwenju/p/16921044.html

相关文章