Follow redirects when downloading files
This commit is contained in:
parent
c901bfb72a
commit
69c7fb8c2f
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
20
src/utils.ts
20
src/utils.ts
|
@ -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', () => {
|
||||||
|
|
Loading…
Reference in New Issue