Skip to content

Instantly share code, notes, and snippets.

@miguelmota
Created June 25, 2024 18:22
Show Gist options
  • Save miguelmota/fb64ea91c20135566791d667497cea6e to your computer and use it in GitHub Desktop.
Save miguelmota/fb64ea91c20135566791d667497cea6e to your computer and use it in GitHub Desktop.
Node.js get npm package downloads ranked for username
import fetch from 'node-fetch'
const username = 'UserNameGoesHere'; // Replace with the npm username
const npmAPI = `https://registry.npmjs.org/-/v1/search?text=maintainer:${username}&size=100`
async function getPackages() {
const response = await fetch(npmAPI)
const data = await response.json()
return data.objects.map(pkg => pkg.package.name)
}
async function getDownloadStatsLastWeek(packageName) {
const oneWeekAgo = new Date()
oneWeekAgo.setDate(oneWeekAgo.getDate() - 7)
const startDate = oneWeekAgo.toISOString().split('T')[0]
const today = new Date().toISOString().split('T')[0]
const response = await fetch(`https://api.npmjs.org/downloads/point/${startDate}:${today}/${packageName}`)
const data = await response.json()
return { packageName, downloads: data.downloads || 0 }
}
async function getDownloadStatsLastMonth(packageName) {
const response = await fetch(`https://api.npmjs.org/downloads/point/last-month/${packageName}`)
const data = await response.json()
return { packageName, downloads: data.downloads || 0 }
}
async function getDownloadStats(packageName) {
return getDownloadStatsLastWeek(packageName)
// return getDownloadStatsLastMonth(packageName)
}
async function main() {
const packages = await getPackages()
const downloadStats = await Promise.all(packages.map(getDownloadStats))
downloadStats.sort((a, b) => b.downloads - a.downloads)
console.log(downloadStats)
}
main().catch(console.error)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment