跳到主要内容

文件系统路由

2 分钟阅读

概述

"文件系统路由" 通常是指将文件系统中的文件和文件夹映射到 Web 应用程序的不同 URL 路径,以便通过 Web 服务器来访问这些文件和文件夹。这是一种常见的用于构建静态网站或单页应用程序(SPA)的技术。

简单的文件路由算法实现

import express, { Router } from "express";
import fs from "fs";
import path from "path";
import chalk from "chalk"
// 创建路由对象
const router: Router = express.Router();

// 用于存储已存在的路由路径
const existingPaths = new Set();

function loadRoutes(routeFolder: string, parentPath = "") {
const files = fs.readdirSync(routeFolder);
files.forEach(async (file) => {
const filePath = path.join(routeFolder, file);
const isDirectory = fs.statSync(filePath).isDirectory();
if (isDirectory) {
// 如果是文件夹,递归加载子文件夹中的路由文件
let subfolder = path.join(parentPath, file);
subfolder = subfolder.startsWith("/") ? subfolder : `/${subfolder}`;
loadRoutes(filePath, subfolder);
} else if ((file.endsWith(".js") || file.endsWith(".ts")) && !file.endsWith(".d.ts")) {
// 如果是路由文件,导入并注册路由
const routePath = path.parse(file).name === 'index' ? `${parentPath}` : `${parentPath}/${path.parse(file).name}`;
// 检查是否存在重复路由路径
if (existingPaths.has(routePath)) {
console.warn(chalk.yellow("[Warning]"),`重复的路由路径: ${routePath} (${filePath})`);
// 可以采取适当的措施来处理重复路径,如抛出异常或其他处理
} else {
existingPaths.add(routePath);
const route = await import(filePath);
router.use(routePath, route.router);
}
}
});
}

// 调用函数开始递归加载路由文件
const routesFolderPath = path.join(__dirname, "routes");
loadRoutes(routesFolderPath);

router.use(apiLimiter);

export default router;
评论
0条评论

添加新评论

昵称
邮箱
网址