| 45 | * @returns |
| 46 | */ |
| 47 | export function dirPath(path: string): string { |
| 48 | const fam = family(); |
| 49 | // const fam = "windows"; // vitest 测试时打开此行注释 |
| 50 | |
| 51 | if (fam === "windows") { |
| 52 | path = path.replace(/\\/g, "/"); // 将反斜杠替换为正斜杠 |
| 53 | } |
| 54 | |
| 55 | const file = path.split("/").pop(); // 获取文件名 |
| 56 | if (!file) { |
| 57 | throw new Error("Invalid path"); |
| 58 | } |
| 59 | |
| 60 | let directory = path.substring(0, path.length - file.length); // 获取目录路径 |
| 61 | if (directory.endsWith("/")) { |
| 62 | directory = directory.slice(0, -1); // 如果目录路径以斜杠结尾,去掉最后的斜杠 |
| 63 | } |
| 64 | |
| 65 | if (fam === "windows") { |
| 66 | // 再换回反斜杠 |
| 67 | return directory.replace(/\//g, "\\"); |
| 68 | } |
| 69 | |
| 70 | return directory; // 返回目录路径 |
| 71 | } |
| 72 | |
| 73 | /** |
| 74 | * 通过路径字符串中,提取出文件名 |