(url, destination, redirectCount = 0)
| 67 | |
| 68 | // Download file from URL |
| 69 | function downloadFile(url, destination, redirectCount = 0) { |
| 70 | return new Promise((resolve, reject) => { |
| 71 | if (redirectCount > 5) { |
| 72 | return reject(new Error("Too many redirects while downloading file")) |
| 73 | } |
| 74 | |
| 75 | const file = fs.createWriteStream(destination) |
| 76 | https.get(url, (response) => { |
| 77 | if (response.statusCode === 302 || response.statusCode === 301) { |
| 78 | // Handle redirects |
| 79 | // Close the current file and delete it |
| 80 | // Then download from the new location |
| 81 | file.close() |
| 82 | safeUnlink(destination) |
| 83 | return downloadFile(response.headers.location, destination, redirectCount + 1) |
| 84 | .then(resolve) |
| 85 | .catch(reject) |
| 86 | } |
| 87 | |
| 88 | if (response.statusCode !== 200) { |
| 89 | file.close() |
| 90 | safeUnlink(destination) |
| 91 | return reject(new Error(`Failed to download: ${response.statusCode} ${response.statusMessage}`)) |
| 92 | } |
| 93 | |
| 94 | response.pipe(file) |
| 95 | file.on('finish', () => { |
| 96 | file.close(resolve) |
| 97 | }) |
| 98 | }).on('error', (err) => { |
| 99 | safeUnlink(destination) |
| 100 | reject(err) |
| 101 | }) |
| 102 | }) |
| 103 | } |
| 104 | |
| 105 | // Calculate SHA-256 hash of a file |
| 106 | function calculateSHA256(filePath) { |
no test coverage detected