1. 方案一、request
const request = require("request")
const fs = require('fs');
const progress = require('progress-stream')
const https = require("https")
const http = require("http")
let url = "https://archive.apache.org/dist/maven/maven-3/3.8.5/binaries/apache-maven-3.8.5-bin.zip"
let targetUrl = `E:\\development\\myProject\\pc-dev-tool\\download\\apache-maven-3.8.5-bin.zip`
async function downloadUrlFile(url, targetUrl) {
let stream = fs.createWriteStream(targetUrl)
let p = await setDownloadProgress(url, fn)
let downloadRequest = request(url)
downloadRequest.pipe(p).pipe(stream)
}
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, fn) {
let p = progress({
length: await getUrlFileSize(url),
time: 500
})
p.on('progress', progress => {
console.log("下载进度:", progress.percentage)
});
return p
}
downloadUrlFile(url,targetUrl)
2. 方案二、fetch
注:node-fetch版本过高可能会报错,当前用的是 “node-fetch”: “^2.6.1”
const fetch = require('node-fetch')
const fs = require('fs');
const progressStream = require('progress-stream')
const AbortController = require("abort-controller")
let url = "https://archive.apache.org/dist/maven/maven-3/3.8.5/binaries/apache-maven-3.8.5-bin.zip"
let target = `E:\\development\\myProject\\pc-dev-tool\\download\\apache-maven-3.8.5-bin.zip`
const fileStream = fs.createWriteStream(target).on('error', function(e) {
console.error('错误', e)
}).on('ready', function() {
console.log("开始下载:");
}).on('finish', function() {
console.log('文件下载完成:');
});
fetch(url, {
method: 'GET',
headers: {
'Content-Type': 'application/octet-stream'
},
}).then(res => {
let length = res.headers.get("content-length");
let str = progressStream({
length,time: 100
});
str.on('progress', function(progressData) {
let percentage = Math.round(progressData.percentage) + '%';
console.log(percentage);
});
res.body.pipe(str).pipe(fileStream);
}).catch(e => {
console.log(e);
});
|