UNPKG

nginx-binaries

Version:

A downloader for nginx and njs standalone binaries.

51 lines 2.12 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.downloadFile = void 0; const crypto = require("node:crypto"); const node_fs_1 = require("node:fs"); const node_path_1 = require("node:path"); const stream = require("node:stream"); const node_util_1 = require("node:util"); const fetch_1 = require("./fetch"); const logger_1 = require("../logger"); const streamPipeline = (0, node_util_1.promisify)(stream.pipeline); async function downloadFile(url, checksum, filepath, fetchOpts) { if (await checkFileChecksum(filepath, checksum)) { logger_1.log.debug(`File ${filepath} already exists`); return filepath; } const [hashAlg, expectedHash] = splitChecksumValue(checksum); const hash = crypto.createHash(hashAlg); logger_1.log.info(`Downloading ${url}...`); (0, node_fs_1.mkdirSync)((0, node_path_1.dirname)(filepath), { recursive: true }); const resp = await (0, fetch_1.fetch)(url, fetchOpts); await streamPipeline(resp.body.on('data', chunk => hash.update(chunk)), (0, node_fs_1.createWriteStream)(filepath, { flags: 'w', mode: 0o0755 })); if (hash.digest('hex') !== expectedHash) { throw Error(`File ${(0, node_path_1.basename)(filepath)} is corrupted, ${hashAlg} checksum doesn't match!`); } logger_1.log.debug(`File was saved in ${filepath}`); return filepath; } exports.downloadFile = downloadFile; async function checkFileChecksum(filepath, checksum) { const [hashAlg, expectedHash] = splitChecksumValue(checksum); const hash = crypto.createHash(hashAlg); try { await streamPipeline((0, node_fs_1.createReadStream)(filepath), hash); return hash.digest('hex') === expectedHash; } catch (err) { if (err.code === 'ENOENT' || err.code === 'EISDIR') { return false; } throw err; } } function splitChecksumValue(checksum) { const [alg, value] = checksum.split(':', 2); if (!alg || !value) { throw RangeError(`Invalid checksum value: ${checksum}`); } return [alg, value]; } //# sourceMappingURL=downloadFile.js.map