♻ Refactor download wrapper into async func

This commit is contained in:
C-3PO 2018-10-05 14:56:43 +02:00
parent 32d61a3559
commit 35dfc7483d
Signed by: c3po
GPG key ID: 62993C4BB4D86F24
2 changed files with 25 additions and 20 deletions

View file

@ -9,6 +9,9 @@ export default function downloadWithCurl({ host, path, tempFileName, size, resol
const parameters: string[] = [ const parameters: string[] = [
//... //...
'--limit-rate', '30m', //maximum speed of 30 MB/s = 240 MBit/s
'--speed-limit', String(100 * 1024 * 1024), //abort if less than 100 MB in 15 seconds
'--speed-time', '15',
'--output', tempFileName, '--output', tempFileName,
url, url,
]; ];

View file

@ -6,27 +6,29 @@ import checkLocalCache from './funcs/checkLocalCache';
import createDirRecursively from './funcs/createDirRecursively'; import createDirRecursively from './funcs/createDirRecursively';
/** Downloads the given URL and saves it to disk. Returns the location where file is saved under. Throws error if download fails. */ /** Downloads the given URL and saves it to disk. Returns the location where file is saved under. Throws error if download fails. */
export default function downloadWrapper({ host, path, size, useCurl = false }: {host: string, path: string, size: number, useCurl: boolean}): Promise<string> { export default async function downloadWrapper({ host, path, size, useCurl = false }: {host: string, path: string, size: number, useCurl: boolean}): string {
return new Promise((resolve, reject) => { //Generate file name we want to save it under
//Generate file name we want to save it under //e.g. on Linux: /tmp/patcher/patch/assets_swtor_main/assets_swtor_main_-1to0/assets_swtor_main_-1to0.zip
//e.g. on Linux: /tmp/patcher/patch/assets_swtor_main/assets_swtor_main_-1to0/assets_swtor_main_-1to0.zip const tempFileName = nodePath.join(os.tmpdir(), 'patcher', host, path);
const tempFileName = nodePath.join(os.tmpdir(), 'patcher', host, path);
//Create parent directory recursively //Create parent directory recursively
const folderName = nodePath.dirname(tempFileName); const folderName = nodePath.dirname(tempFileName);
createDirRecursively(folderName).then(() => { await createDirRecursively(folderName);
//Check if file already exists locally
checkLocalCache(tempFileName, size).then((cacheStatus) => {
if (cacheStatus) {
return resolve(tempFileName);
}
if (useCurl) { //Check if file already exists locally
downloadWithCurl({ host, path, tempFileName, size, resolve, reject }); const cacheStatus = await checkLocalCache(tempFileName, size);
} else { if (cacheStatus) {
downloadUrlContents(host, path, tempFileName, resolve, reject); return tempFileName;
} }
});
//Download either via curl or natively with Node
if (useCurl) {
await new Promise((resolve, reject) => {
downloadWithCurl({ host, path, tempFileName, size, resolve, reject });
}); });
}); } else {
await new Promise((resolve, reject) => {
downloadUrlContents(host, path, tempFileName, resolve, reject);
});
}
} }