-
Notifications
You must be signed in to change notification settings - Fork 39
Expand file tree
/
Copy pathinternals.js
More file actions
83 lines (75 loc) · 2.2 KB
/
internals.js
File metadata and controls
83 lines (75 loc) · 2.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
const { createWriteStream, createReadStream } = require("fs");
const { pipeline } = require("stream/promises");
const { extract } = require("tar");
const { readFile } = require("fs/promises");
const { createHash } = require("crypto");
const https = require("follow-redirects").https;
function downloadFile(url, path, retries = 3) {
return new Promise((resolve, reject) => {
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);
});
}
async function extractTar(path, dest) {
await extract({ file: path, sync: false, cwd: dest });
}
async function verifyFileHash(filepath) {
const expectedHash = (await readFile(`${filepath}.sha256sum`, "utf8")).split(
" "
)[0];
const input = createReadStream(filepath);
const hashBuilder = createHash("sha256");
await pipeline(input, hashBuilder);
const hash = hashBuilder.digest("hex");
if (hash !== expectedHash) {
console.log(`Expected: ${expectedHash}`);
console.log(`Actual: ${hash}`);
throw new Error(`File hash mismatch for ${filepath}`);
}
}
module.exports = {
downloadFile,
extractTar,
verifyFileHash,
};