npm-install-size
Version:
Check the install size of any NPM package before installing it.
96 lines (90 loc) • 2.86 kB
JavaScript
import fs from 'fs/promises';
import path from 'path';
export async function getDirStats(dir) {
let total = 0;
let count = 0;
let largest = { name: null, size: 0 };
async function walk(current) {
const entries = await fs.readdir(current, { withFileTypes: true });
for (const entry of entries) {
const fullPath = path.join(current, entry.name);
if (entry.isDirectory()) {
await walk(fullPath);
} else if (entry.isFile()) {
const stat = await fs.stat(fullPath);
total += stat.size;
count++;
if (stat.size > largest.size) {
largest = { name: path.relative(dir, fullPath), size: stat.size };
}
}
}
}
await walk(dir);
return { total, count, largest };
}
export async function getAllFilesWithSizes(dir) {
const files = [];
async function walk(current) {
const entries = await fs.readdir(current, { withFileTypes: true });
for (const entry of entries) {
const fullPath = path.join(current, entry.name);
if (entry.isDirectory()) {
await walk(fullPath);
} else if (entry.isFile()) {
const stat = await fs.stat(fullPath);
files.push({ path: path.relative(dir, fullPath), size: stat.size });
}
}
}
await walk(dir);
return files;
}
export function getFileTypeBreakdown(files) {
const breakdown = {};
for (const f of files) {
const ext = path.extname(f.path) || 'NOEXT';
breakdown[ext] = (breakdown[ext] || 0) + f.size;
}
return breakdown;
}
export function estimateDownloadTime(bytes, mbps = 10) {
// mbps: megabits per second
const bits = bytes * 8;
const seconds = bits / (mbps * 1_000_000);
if (seconds < 1) return '<1s';
if (seconds < 60) return `${Math.round(seconds)}s`;
return `${Math.floor(seconds / 60)}m ${Math.round(seconds % 60)}s`;
}
export async function cleanup(dir) {
try {
await fs.rm(dir, { recursive: true, force: true });
} catch {}
}
export async function findMainJsFile(dir) {
// Try to find main entry from package.json, fallback to index.js
try {
const pkgJsonPath = path.join(dir, 'package.json');
const pkgJson = JSON.parse(await fs.readFile(pkgJsonPath, 'utf8'));
let main = pkgJson.module || pkgJson.main;
if (main) {
const mainPath = path.join(dir, main);
try {
await fs.access(mainPath);
return mainPath;
} catch {}
}
} catch {}
// Fallback to index.js
const fallback = path.join(dir, 'index.js');
try {
await fs.access(fallback);
return fallback;
} catch {}
// Otherwise, try to find any .js file
const files = await fs.readdir(dir);
for (const file of files) {
if (file.endsWith('.js')) return path.join(dir, file);
}
return null;
}