UNPKG

@moonsong-labs/moonwall-cli

Version:

Testing framework for the Moon family of projects

58 lines (56 loc) 1.55 kB
// src/internal/downloader.ts import { SingleBar, Presets } from "cli-progress"; import fetch from "node-fetch"; import fs from "node:fs"; var progressBar; var onStart = (length) => { progressBar = new SingleBar( { etaAsynchronousUpdate: true, etaBuffer: 40, format: "Downloading: [{bar}] {percentage}% | ETA: {eta_formatted} | {value}/{total}" }, Presets.shades_classic ); progressBar.start(length, 0); }; var onProgress = (bytes) => { progressBar.update(bytes); }; var onComplete = () => { progressBar.stop(); process.stdout.write(` \u{1F4BE} Saving binary artefact...`); }; async function downloader(url, outputPath) { const tempPath = outputPath + ".tmp"; const writeStream = fs.createWriteStream(tempPath); let transferredBytes = 0; const response = await fetch(url); const readStream = response.body; readStream.pipe(writeStream); await new Promise((resolve, reject) => { const contentLength = parseInt(response.headers.get("Content-Length") || "0"); onStart(contentLength); readStream.on("data", (chunk) => { transferredBytes += chunk.length; onProgress(transferredBytes); }); readStream.on("end", () => { writeStream.end(); onComplete(); writeStream.close(() => resolve("Finished!")); }); readStream.on("error", () => { reject("Error!"); }); }); try { fs.writeFileSync(outputPath, fs.readFileSync(tempPath)); fs.rmSync(tempPath); } catch (e) { throw new Error(e); } } export { downloader };