Skip to content

Instantly share code, notes, and snippets.

@Nurou
Last active December 25, 2023 19:51
Show Gist options
  • Save Nurou/14e223469196a2524f4cf363037b2b48 to your computer and use it in GitHub Desktop.
Save Nurou/14e223469196a2524f4cf363037b2b48 to your computer and use it in GitHub Desktop.
npm download counts for a package using npm stats. Hardcoded for 2023
const fs = require("fs");
async function getDownloadsPerDay(pkgName) {
// for the past year
const from = "2022-12-01";
const until = "2023-11-30";
try {
const res = await fetch(
`https://npm-stat.com/api/download-counts?package=${pkgName}&from=${from}&until=${until}`,
);
const json = await res.json();
return json;
} catch (error) {
console.error(`Error fetching downloads: ${error.message}`);
throw error;
}
}
function writeToCSV(monthlyDownloads, packageName) {
const csvData = [["date", "downloads"]];
for (const [date, downloadCount] of Object.entries(monthlyDownloads)) {
csvData.push([date, downloadCount]);
}
const csvString = csvData.map((row) => row.join(",")).join("\n");
const filename = `${packageName}-monthly-downloads.csv`;
fs.writeFileSync(filename, csvString, "utf-8");
console.log(`CSV data has been saved to ${filename}`);
}
function convertToMonthlyDownloads(dailyData) {
const monthlyData = {};
for (const date in dailyData) {
const [year, month] = date.split("-");
const day = "15"; // use middle of month for scatter plot
const yearMonth = `${year}-${month}-${day}`;
if (monthlyData[yearMonth]) {
monthlyData[yearMonth] += dailyData[date];
} else {
monthlyData[yearMonth] = dailyData[date];
}
}
return monthlyData;
}
function calculatePercentChange(monthlyDownloads) {
const dates = Object.keys(monthlyDownloads);
const firstDate = dates[0];
const lastDate = dates[dates.length - 1];
const firstCount = monthlyDownloads[firstDate];
const lastCount = monthlyDownloads[lastDate];
const percentChange = ((lastCount - firstCount) / firstCount) * 100;
console.log("percentChange: ", `${percentChange.toFixed(2)}%`);
}
async function main() {
const pkgName = process.argv[2];
const downloads = await getDownloadsPerDay(pkgName);
const monthlyDownloads = convertToMonthlyDownloads(downloads[pkgName]);
calculatePercentChange(monthlyDownloads);
writeToCSV(monthlyDownloads, pkgName);
}
main();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment