-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathget_npm_downloads_count.js
More file actions
75 lines (64 loc) · 1.95 KB
/
get_npm_downloads_count.js
File metadata and controls
75 lines (64 loc) · 1.95 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
import fs from "fs/promises";
import path from "path";
async function fetchNpmDownloadsCountTotal() {
const response = await fetch(
"https://api.npmjs.org/downloads/point/2000-01-01:2100-01-01/daisyui",
);
if (!response.ok) {
throw new Error("Failed to fetch total npm downloads count");
}
const data = await response.json();
return data.downloads;
}
async function fetchNpmDownloadsCountWeekly() {
const response = await fetch(
"https://api.npmjs.org/downloads/point/last-week/daisyui",
);
if (!response.ok) {
throw new Error("Failed to fetch weekly npm downloads count");
}
const data = await response.json();
return data.downloads;
}
async function readStatsFile(filePath) {
try {
const fileContent = await fs.readFile(filePath, "utf-8");
return JSON.parse(fileContent);
} catch (error) {
if (error.code === "ENOENT") {
return {};
}
throw error;
}
}
async function writeStatsFile(filePath, data) {
await fs.writeFile(filePath, JSON.stringify(data, null, 2), "utf-8");
}
async function updateDownloadsCount() {
const filePath = path.resolve("docs", "stats.json");
try {
const [totalDownloadsCount, weeklyDownloadsCount] = await Promise.all([
fetchNpmDownloadsCountTotal(),
fetchNpmDownloadsCountWeekly(),
]);
const fileData = await readStatsFile(filePath);
let updated = false;
if (fileData.npm_downloads_count_total !== totalDownloadsCount) {
fileData.npm_downloads_count_total = totalDownloadsCount;
updated = true;
}
if (fileData.npm_downloads_count_weekly !== weeklyDownloadsCount) {
fileData.npm_downloads_count_weekly = weeklyDownloadsCount;
updated = true;
}
if (updated) {
await writeStatsFile(filePath, fileData);
console.log("Downloads count updated.");
} else {
console.log("Downloads count has not changed.");
}
} catch (error) {
console.error("Error:", error);
}
}
updateDownloadsCount();