-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
56 lines (47 loc) · 1.27 KB
/
index.js
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
const axios = require("axios");
async function getFileSize(
url,
format = "bytes",
timeout = 20000,
maxAttempts = 4
) {
const urlRegex = /^(https?:\/\/)/;
if (typeof url !== "string" || url.length === 0 || !urlRegex.test(url)) {
throw new Error("Invalid URL");
}
let attempts = 0;
while (attempts < maxAttempts) {
try {
const response = await axios.get(url, {
responseType: "stream",
timeout,
});
let fileSizeInBytes = 0;
const contentLength = response.headers["content-length"];
if (contentLength) {
fileSizeInBytes = parseInt(contentLength, 10);
} else {
response.data.on("data", (dataChunk) => {
fileSizeInBytes += dataChunk.length;
});
await new Promise((resolve) => {
response.data.on("end", resolve);
});
}
if (format.toLowerCase() === "kb") {
fileSizeInBytes /= 1024;
} else if (format.toLowerCase() === "mb") {
fileSizeInBytes /= 1048576;
}
return fileSizeInBytes;
} catch (error) {
attempts++;
if (attempts >= maxAttempts) {
throw new Error(
"Sorry We could not get the file size after multiple attempts"
);
}
}
}
}
module.exports = getFileSize;