import * as path from "path";
import * as fs from "fs";
import { URL } from "url";
import * as http from "http";
import * as https from "https";
class Downloader {
public downloadFile(downloaderUrl: URL): void {
if (downloaderUrl.protocol === "http:") {
this.httpDownload(downloaderUrl);
} else if (downloaderUrl.protocol === "https:") {
this.httpsDownload(downloaderUrl);
} else {
console.error(`Downloader is not support ${downloaderUrl.protocol.split(":")[0]} protocol!`);
}
}
private httpDownload(downloaderUrl: URL): void {
let error: Error | null | undefined;
http.get(downloaderUrl, (res) => {
if (res.statusCode === 200) {
let writer = fs.createWriteStream(path.join(__dirname,"http"),"UTF-8");
res.pipe(writer);
writer.on('finnish',()=>{
res.unpipe();
writer.close;
});
} else if (res.statusCode == 302) {
let location = res.headers['location'];
console.log(location);
if(!(location===undefined)){
this.downloadFile(new URL(location));
}
} else {
error = new Error('Request Failed. ' + `Status Code: ${res.statusCode}`);
}
if (!(error === null || error === undefined)) {
console.error(error.message);
res.resume();
return;
}
});
}
private httpsDownload(downloaderUrl: URL): void {
let error: Error | null | undefined;
https.get(downloaderUrl, (res) => {
if (res.statusCode === 200) {
let writer = fs.createWriteStream(path.join(__dirname,"a.html"),"UTF-8");
res.pipe(writer);
writer.on('finnish',()=>{
res.unpipe();
writer.close;
});
} else if (res.statusCode == 302) {
let location = res.headers['location'];
console.log(location);
if(!(location===undefined)){
this.downloadFile(new URL(location));
}
} else {
error = new Error('Request Failed. ' + `Status Code: ${res.statusCode}`);
}
if (!(error === null || error === undefined)) {
console.error(error.message);
res.resume();
return;
}
});
}
}
let httpUrl: URL = new URL("http://url.12306.com/aXANGN")
let html:URL = new URL("https://www.baidu.com/");
let httpsUrl: URL = new URL("https://github.com/gohugoio/hugo/releases/download/v0.52/hugo_extended_0.52_macOS-64bit.tar.gz");
let ftpUrl: URL = new URL("ftp://ftp.freebsd.org/pub/FreeBSD/README.TXT");
let down: Downloader = new Downloader();
//down.downloadFile(httpUrl);
//down.downloadFile(html);
//down.downloadFile(httpsUrl);
//down.downloadFile(ftpUrl);