askrobots / dbbasic-browser
Public
A desktop browser with x402 built in: when a page asks for payment, it pays in stablecoins and shows the content.
danq9
site icons (favicons) in tabs, address bar suggestions and the bookmarks panel
7249579
15 hours, 50 minutes ago
History
disk-usage.ts · 1.9 KB · 61 lines
| 1 | /** |
| 2 | * How much disk a folder uses, and which parts of it. Used to show what the browser's own data folder is made of (cache, |
| 3 | * site storage, service workers…), so growth has a name. Bounded: it stops after MAX_FILES files so a huge folder cannot |
| 4 | * make the status itself the thing that hogs the machine, and says so. |
| 5 | */ |
| 6 | |
| 7 | import { promises as fs } from "node:fs"; |
| 8 | import { join } from "node:path"; |
| 9 | |
| 10 | export interface DiskUsage { |
| 11 | bytes: number; |
| 12 | files: number; |
| 13 | /** True when the walk stopped early: the numbers are a floor. */ |
| 14 | truncated: boolean; |
| 15 | /** The folder's direct children, biggest first. */ |
| 16 | top: Array<{ name: string; bytes: number }>; |
| 17 | } |
| 18 | |
| 19 | const MAX_FILES = 60_000; |
| 20 | |
| 21 | export async function diskUsage(dir: string, opts: { maxFiles?: number; topN?: number } = {}): Promise<DiskUsage> { |
| 22 | const max = opts.maxFiles ?? MAX_FILES; |
| 23 | let files = 0; |
| 24 | let truncated = false; |
| 25 | const sizeOf = async (p: string): Promise<number> => { |
| 26 | if (files >= max) { |
| 27 | truncated = true; |
| 28 | return 0; |
| 29 | } |
| 30 | let st; |
| 31 | try { |
| 32 | st = await fs.lstat(p); // lstat: never follow a link out of the folder |
| 33 | } catch { |
| 34 | return 0; |
| 35 | } |
| 36 | if (st.isSymbolicLink()) return 0; |
| 37 | if (!st.isDirectory()) { |
| 38 | files++; |
| 39 | return st.blocks ? st.blocks * 512 : st.size; // what it takes on disk, not what it claims |
| 40 | } |
| 41 | let names: string[]; |
| 42 | try { |
| 43 | names = await fs.readdir(p); |
| 44 | } catch { |
| 45 | return 0; |
| 46 | } |
| 47 | let sum = 0; |
| 48 | for (const n of names) sum += await sizeOf(join(p, n)); |
| 49 | return sum; |
| 50 | }; |
| 51 | let names: string[] = []; |
| 52 | try { |
| 53 | names = await fs.readdir(dir); |
| 54 | } catch { |
| 55 | return { bytes: 0, files: 0, truncated: false, top: [] }; |
| 56 | } |
| 57 | const top: Array<{ name: string; bytes: number }> = []; |
| 58 | for (const n of names) top.push({ name: n, bytes: await sizeOf(join(dir, n)) }); |
| 59 | top.sort((a, b) => b.bytes - a.bytes); |
| 60 | return { bytes: top.reduce((s, t) => s + t.bytes, 0), files, truncated, top: top.slice(0, opts.topN ?? 8) }; |
| 61 | } |