UNPKG

tezx

Version:

TezX is a modern, ultra-lightweight, and high-performance JavaScript framework built specifically for Bun. It provides a minimal yet powerful API, seamless environment management, and a high-concurrency HTTP engine for building fast, scalable web applicat

54 lines (53 loc) 1.63 kB
import { readdirSync } from "node:fs"; import { join } from "node:path"; import { extensionExtract, } from "../utils/utils.js"; import { sanitizePathSplitBasePath } from "../utils/url.js"; export function serveStatic(...args) { let route = ""; let dir; let options = {}; switch (args.length) { case 3: [route, dir, options] = args; break; case 2: if (typeof args[1] === "object") { [dir, options] = args; } else { [route, dir] = args; } break; case 1: [dir] = args; break; default: throw new Error(`\x1b[1;31m404 Not Found\x1b[0m \x1b[1;32mInvalid arguments\x1b[0m`); } return { files: getFiles(dir, route, options), options, }; } function getFiles(dir, basePath = "/", option = {}) { const files = []; const entries = readdirSync(dir, { withFileTypes: true }); for (const entry of entries) { const fullPath = join(dir, entry.name); if (entry.isDirectory()) { files.push(...getFiles(fullPath, `${basePath}/${entry.name}`, option)); } else { const ext = extensionExtract(entry.name); if (option?.extensions?.length && !option.extensions.includes(ext)) { continue; } files.push({ fileSource: fullPath, route: `/${sanitizePathSplitBasePath(basePath, entry.name).join("/")}`, }); } } return files; } export default serveStatic;