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> { export async function downloadFile(url: string, dest: string, currRedirectDepth: number = 0): Promise<void> {
const getURL = url.toLowerCase().startsWith('http://') ? httpGet : httpsGet; const doGetRequest = url.toLowerCase().startsWith('http://') ? httpGet : httpsGet;
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
let writeStream: WriteStream | null = null; let writeStream: WriteStream | null = null;
const done = function (err: boolean) { const done = function (errored: boolean) {
if (writeStream) { if (writeStream) {
writeStream.close(); writeStream.close();
writeStream = null; writeStream = null;
if (err) { if (errored) {
rmdirSync(dest, {recursive: true}); rmdirSync(dest, {recursive: true});
} }
} }
}; };
// TODO doGetRequest(url, {
getURL(url, {
headers: { headers: {
'User-Agent': userAgent 'User-Agent': userAgent
} }
}, (httpRes) => { }, (httpRes) => {
if (httpRes.statusCode != 200) { 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); done(true);
return reject(new Error(`Server responded with ${httpRes.statusCode}`)); return reject(new Error(`Server responded with ${httpRes.statusCode}`));
} }
}
writeStream = createWriteStream(dest, {encoding: 'binary'}) writeStream = createWriteStream(dest, {encoding: 'binary'})
.on('finish', () => { .on('finish', () => {