From ed1d0c35da6be9d9aadbdacb38fff36b90742de1 Mon Sep 17 00:00:00 2001 From: Alan Pearce Date: Mon, 1 Apr 2024 19:40:45 +0200 Subject: Simplify walkDirectory by using recursive readdir --- src/app.ts | 24 +++++++++--------------- 1 file changed, 9 insertions(+), 15 deletions(-) (limited to 'src') diff --git a/src/app.ts b/src/app.ts index ac11c4d..e0fe2e8 100644 --- a/src/app.ts +++ b/src/app.ts @@ -1,5 +1,6 @@ import path from "node:path"; -import fs, { Stats } from "node:fs"; +import fs from "node:fs/promises"; +import type { Stats } from "node:fs"; import type { BunFile, Serve } from "bun"; import * as Sentry from "@sentry/node"; import prom from "bun-prometheus-client"; @@ -73,21 +74,14 @@ function registerFile( }); } -function walkDirectory(root: string, dir: string) { - const absDir = path.join(root, dir); - for (let pathname of fs.readdirSync(absDir)) { - const relPath = path.join(dir, pathname); - const absPath = path.join(absDir, pathname); - const stat = fs.statSync(absPath); - if (stat.isDirectory()) { - walkDirectory(root, relPath + path.sep); - } else if (stat.isFile()) { - if (pathname.startsWith("index.html")) { +async function walkDirectory(root: string) { + for (let relPath of await fs.readdir(root, { recursive: true })) { + const absPath = path.join(root, relPath); + const stat = await fs.stat(absPath); + if (stat.isFile()) { + if (relPath.endsWith("index.html")) { const dir = relPath.replace("index.html", ""); registerFile(relPath, dir, absPath, stat); - if (dir !== "") { - registerFile(relPath, dir + path.sep, absPath, stat); - } } else { registerFile(relPath, relPath, absPath, stat); } @@ -95,7 +89,7 @@ function walkDirectory(root: string, dir: string) { } } -walkDirectory("public/", ""); +await walkDirectory("public/"); async function serveFile( file: File, -- cgit 1.4.1