diff --git a/bin/install-kwix.js b/bin/install-kwix.js index 6f0ae2f..16ea2ce 100644 --- a/bin/install-kwix.js +++ b/bin/install-kwix.js @@ -46,22 +46,24 @@ function download(url, dest, redirectsLeft = MAX_REDIRECTS) { const req = https.get(url, {agent}, res => { if (res.statusCode >= 300 && res.statusCode < 400 && res.headers.location) { - res.resume(); // discard body + res.resume(); file.close(); if (redirectsLeft <= 0) { reject(new Error(`Too many redirects while downloading ${url}`)); return; } - // Location can be relative, so resolve it against the current URL. + const nextUrl = new URL(res.headers.location, url).toString(); resolve(download(nextUrl, dest, redirectsLeft - 1)); return; } + if (!res.statusCode || res.statusCode >= 400) { res.resume(); cleanupAndReject(new Error(`HTTP ${res.statusCode} - ${res.statusMessage}`)); return; } + res.pipe(file); file.on('finish', () => { file.close(resolve); @@ -85,12 +87,19 @@ async function flattenExtractedDir(srcDir, destDir) { for (const entry of entries) { const src = path.join(sourceDir, entry.name); const dest = path.join(destDir, entry.name); - await fs.promises.rename(src, dest); + + await fs.promises.cp(src, dest, { + recursive: true, + force: true + }); + + await fs.promises.rm(src, {recursive: true, force: true}); } } async function extractTarGz(archivePath, destDir) { const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'kiwix-extract-')); + await tar.extract({ file: archivePath, cwd: tmpDir @@ -103,6 +112,7 @@ async function extractTarGz(archivePath, destDir) { async function extractZip(archivePath, destDir) { const zip = new AdmZip(archivePath); const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'kiwix-extract-')); + await new Promise((resolve, reject) => { zip.extractAllToAsync(tmpDir, true, false, err => { if (err) reject(err); @@ -159,6 +169,7 @@ async function install() { if (entry.startsWith('kiwix-')) { const fullPath = path.join(BIN_DIR, entry); const stat = await fs.promises.stat(fullPath); + if (stat.isFile()) { await fs.promises.chmod(fullPath, 0o755); }