|
| 1 | +import fetch from 'node-fetch'; |
| 2 | +import util from 'util'; |
| 3 | +import fs from 'fs'; |
| 4 | +import path from 'path'; |
| 5 | +import stream from 'stream'; |
| 6 | +import { mkdirp } from 'fs-extra'; |
| 7 | +import Progress from 'progress'; |
| 8 | + |
| 9 | +const streamPipeline = util.promisify(stream.pipeline); |
| 10 | + |
| 11 | +function progressBar(tokens: string, total: number): stream.PassThrough { |
| 12 | + const pt = new stream.PassThrough(); |
| 13 | + const bar = new Progress(tokens, { total }); |
| 14 | + pt.on('pipe', () => { |
| 15 | + pt.on('data', chunk => bar.tick(chunk.length)); |
| 16 | + }); |
| 17 | + return pt; |
| 18 | +} |
| 19 | + |
| 20 | +const macOsLink = |
| 21 | + 'https://download.qt.io/online/qtsdkrepository/mac_x64/desktop/qt5_5130/qt.qt5.5130.clang_64/5.13.0-0-201906171525qtbase-MacOS-MacOS_10_13-Clang-MacOS-MacOS_10_13-X86_64.7z'; |
| 22 | + |
| 23 | +type DownloadOptions = { |
| 24 | + name?: string; |
| 25 | +}; |
| 26 | +async function downloadArchive(archiveLink: string, outPath: string, options: DownloadOptions = {}): Promise<void> { |
| 27 | + const name = options.name || ''; |
| 28 | + const response = await fetch(archiveLink); |
| 29 | + if (!response.ok) { |
| 30 | + throw new Error(`Error while downloading ${name}:${archiveLink}. ${response.statusText}`); |
| 31 | + } |
| 32 | + await mkdirp(path.dirname(outPath)); |
| 33 | + const total = parseInt(`${response.headers.get('content-length')}`, 10); |
| 34 | + const totalInMb = (total / 1024 / 1024).toFixed(2); |
| 35 | + await streamPipeline( |
| 36 | + response.body, |
| 37 | + progressBar(`Downloading ${name} [:bar] :percent of ${totalInMb}MB :etas`, total), |
| 38 | + fs.createWriteStream(outPath), |
| 39 | + ); |
| 40 | +} |
| 41 | + |
| 42 | +const main = async (): Promise<void> => { |
| 43 | + await downloadArchive(macOsLink, './out/download.7zip', { name: 'Qt for Mac' }); |
| 44 | +}; |
| 45 | + |
| 46 | +main() |
| 47 | + .then(console.log) |
| 48 | + .catch(console.error); |
0 commit comments