Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
57 changes: 46 additions & 11 deletions scripts/helpers/internals.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,18 +5,53 @@ const { readFile } = require("fs/promises");
const { createHash } = require("crypto");
const https = require("follow-redirects").https;

function downloadFile(url, path) {
function downloadFile(url, path, retries = 3) {
return new Promise((resolve, reject) => {
const stream = createWriteStream(path);
https
.get(url, (response) => {
response.pipe(stream);
})
.on("error", reject);

stream.on("finish", () => {
stream.close(resolve);
});
const attempt = (remaining) => {
const stream = createWriteStream(path);
let settled = false;
const cleanup = () => {
stream.removeAllListeners("finish");
stream.removeAllListeners("error");
};
const onError = (err) => {
if (!settled) {
settled = true;
cleanup();
if (remaining > 0) {
stream.close(() => {
console.error(
`Download failed, retrying... (${remaining} attempts left)`
);
setTimeout(() => {
attempt(remaining - 1);
}, 1000); // Wait 1 second before retrying
});
} else {
reject(err);
}
}
};
const onFinish = () => {
if (!settled) {
settled = true;
cleanup();
stream.close(resolve);
}
};

// Send http request to download the file
https
.get(url, (response) => {
response.pipe(stream);
})
.on("error", onError);
stream.on("finish", onFinish);
stream.on("error", onError);
};

// Start the first attempt
attempt(retries);
});
}

Expand Down
Loading