Follow redirects when downloading files

This commit is contained in:
Christian Koop 2020-11-24 11:47:15 +01:00
parent c901bfb72a
commit 69c7fb8c2f
No known key found for this signature in database
GPG Key ID: DECCA4CEE0E46D6D
3 changed files with 18 additions and 10 deletions

2
dist/index.js generated vendored

File diff suppressed because one or more lines are too long

2
dist/index.js.map generated vendored

File diff suppressed because one or more lines are too long

View File

@ -60,34 +60,42 @@ export async function runCmd(cmd: string, args: string[], workingDir: string, lo
});
}
export async function downloadFile(url: string, dest: string): Promise<void> {
const getURL = url.toLowerCase().startsWith('http://') ? httpGet : httpsGet;
export async function downloadFile(url: string, dest: string, currRedirectDepth: number = 0): Promise<void> {
const doGetRequest = url.toLowerCase().startsWith('http://') ? httpGet : httpsGet;
return new Promise((resolve, reject) => {
let writeStream: WriteStream | null = null;
const done = function (err: boolean) {
const done = function (errored: boolean) {
if (writeStream) {
writeStream.close();
writeStream = null;
if (err) {
if (errored) {
rmdirSync(dest, {recursive: true});
}
}
};
// TODO
getURL(url, {
doGetRequest(url, {
headers: {
'User-Agent': userAgent
}
}, (httpRes) => {
if (httpRes.statusCode != 200) {
// Follow redirect
if (currRedirectDepth < 12 &&
(httpRes.statusCode == 301 || httpRes.statusCode == 302 || httpRes.statusCode == 303 ||
httpRes.statusCode == 307 || httpRes.statusCode == 308)) {
return downloadFile(url, dest, ++currRedirectDepth)
.then(resolve)
.catch(reject);
} else {
done(true);
return reject(new Error(`Server responded with ${httpRes.statusCode}`));
}
}
writeStream = createWriteStream(dest, {encoding: 'binary'})
.on('finish', () => {