UNPKG

@hx-midway/static-file

Version:

Midwayjs static-file alias 自动扫描,支持路径索引,允许 /path/index.html -> /path/

46 lines (45 loc) 2.05 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.getIndexFiles = void 0; const promises_1 = require("fs/promises"); const path_1 = require("path"); /** * 获取指定目录及其子目录中所有的index.html文件路径 * @param rootPath 要搜索的根目录路径 * @param tplExt 模板文件后缀名,默认为.html * @returns Promise<Record<string, string>> 返回一个对象,键是目录路径,值是index.html的完整路径 */ async function getIndexFiles(rootPath, tplExt = ".html") { if (!rootPath) return {}; const result = {}; // 解析为绝对路径,避免相对路径问题 const absoluteRoot = (0, path_1.resolve)(rootPath); /** * 递归处理目录 * @param currentPath 当前处理的目录路径 */ async function processDirectory(currentPath) { // 读取目录内容,包含文件类型信息 const entries = await (0, promises_1.readdir)(currentPath, { withFileTypes: true }); // 检查当前目录是否包含index.html文件 const hasIndex = entries.some(entry => entry.isFile() && entry.name === `index${tplExt}`); if (hasIndex) { // 获取相对于根目录的路径 const relativePath = currentPath.replace(absoluteRoot, ''); // 存储两种格式的路径:带斜杠和不带斜杠 if (relativePath) result[relativePath] = (0, path_1.join)(relativePath, `index${tplExt}`); result[`${relativePath}/`] = (0, path_1.join)(relativePath, `index${tplExt}`); } // 过滤出子目录(排除符号链接) const subDirectories = entries .filter(entry => entry.isDirectory() && !entry.isSymbolicLink()) .map(entry => processDirectory((0, path_1.join)(currentPath, entry.name))); // 并行处理所有子目录 await Promise.all(subDirectories); } await processDirectory(absoluteRoot); return result; } exports.getIndexFiles = getIndexFiles;