UNPKG

@e.fe/filesize

Version:
74 lines (70 loc) 2.18 kB
// src/analyze.ts import fs2 from "node:fs/promises"; import path from "node:path"; import process from "node:process"; import { filesize } from "filesize"; import { glob } from "glob"; import color from "picocolors"; // src/gzip.ts import fs from "node:fs/promises"; async function getGzipSize(filePath) { const content = await fs.readFile(filePath); return new Promise((resolve) => { import("node:zlib").then(({ gzip }) => { gzip(content, (err, result) => { if (err) resolve(0); else resolve(result.length); }); }); }); } // src/analyze.ts async function analyze(target = "dist", { pattern = "*.@(js|mjs|cjs)" } = {}) { let patternPath; const stats = await fs2.stat(target).catch(() => null); if (stats && stats.isDirectory()) { patternPath = `${target}/**/${pattern}`; } else { patternPath = target; } console.log(color.cyan(`Using pattern: ${patternPath}`)); const files = await glob(patternPath, { nodir: true }); if (files.length === 0) { console.log(color.yellow("Not found any files")); return; } const filesWithSize = await Promise.all( files.map(async (file) => { const stats2 = await fs2.stat(file); return { path: file, size: stats2.size, gzip: await getGzipSize(file) }; }) ); filesWithSize.sort((a, b) => b.size - a.size); const totalSize = filesWithSize.reduce((acc, file) => acc + file.size, 0); const totalGzip = filesWithSize.reduce((acc, file) => acc + file.gzip, 0); console.log(color.bold("\n\u{1F4E6} File size analysis report:\n")); filesWithSize.forEach((file) => { const relativePath = path.relative(process.cwd(), file.path); const percentage = (file.size / totalSize * 100).toFixed(1); console.log( color.blue(relativePath.padEnd(50)), color.yellow(filesize(file.size).padEnd(15)), color.green(`(gzip: ${filesize(file.gzip)})`), color.gray(`${percentage}%`) ); }); console.log(` ${color.bold("Total:")}`); console.log(color.yellow(`Raw: ${filesize(totalSize)}`)); console.log(color.green(`Gzip: ${filesize(totalGzip)}`)); } export { analyze };