|
1 |
| -import * as https from "https"; |
2 |
| -import * as http from "http"; |
3 | 1 | import * as fs from "fs";
|
| 2 | +import * as download from "download"; |
| 3 | +import * as url from "url"; |
4 | 4 |
|
5 |
| -const downloadClocCli = (clocExeDownloadUrl: string, downloadFinishedCallback: () => void) => { |
6 |
| - const clocExeFilename = "cloc.exe"; |
7 |
| - const clocExeFile = fs.createWriteStream(clocExeFilename); |
| 5 | +const downloadClocCli = (clocExeDownloadUrl: string, downloadFinishedCallback: (error?: Error) => void) => { |
| 6 | + try { |
| 7 | + const clocExeFilename = "cloc.exe"; |
| 8 | + const downloadUrl = url.parse(clocExeDownloadUrl); |
8 | 9 |
|
9 |
| - console.log(`Downloading cloc.exe from '${clocExeDownloadUrl}'`); |
10 |
| - https.get(clocExeDownloadUrl, (clocExeDownloadResponse: http.IncomingMessage) => { |
11 |
| - https.get(clocExeDownloadResponse.headers["location"].toString(), (redirectionResponse: http.IncomingMessage) => { |
12 |
| - const stream = redirectionResponse.pipe(clocExeFile); |
13 |
| - stream.on("close", () => { |
14 |
| - console.log(`Download is completed.`); |
15 |
| - downloadFinishedCallback(); |
16 |
| - }); |
17 |
| - }); |
18 |
| - }); |
| 10 | + console.log(`Downloading cloc.exe from:`); |
| 11 | + console.log(downloadUrl); |
| 12 | + |
| 13 | + switch (downloadUrl.protocol) { |
| 14 | + case "file:": |
| 15 | + const downloadPath = url.fileURLToPath ? url.fileURLToPath(downloadUrl.href) : downloadUrl.href.slice(5); |
| 16 | + |
| 17 | + console.log(`Copying file from '${downloadPath}'`); |
| 18 | + fs.copyFile(downloadPath, clocExeFilename, (err) => downloadFinishedCallback(err)); |
| 19 | + break; |
| 20 | + case "http:": |
| 21 | + case "https:": |
| 22 | + download(downloadUrl.href).then((data) => fs.writeFile(clocExeFilename, data, (err) => downloadFinishedCallback(err))); |
| 23 | + break; |
| 24 | + default: |
| 25 | + console.log(`Copying file from '${downloadUrl.href}'`); |
| 26 | + fs.copyFile(downloadUrl.href, clocExeFilename, (err) => downloadFinishedCallback(err)); |
| 27 | + break; |
| 28 | + } |
| 29 | + } catch (err) { |
| 30 | + downloadFinishedCallback(err); |
| 31 | + } |
19 | 32 | };
|
20 | 33 |
|
21 | 34 | export default downloadClocCli;
|
0 commit comments