/** * 获取文件的后缀名 * @param fileName 文件名 * @returns 文件后缀名 */ export function getFileExt(fileName: string): string { const index = fileName.lastIndexOf("."); if (index === -1) { return ""; } return fileName.substring(index + 1); } /** * 获取文件全名(包含扩展名) * 该函数接收一个表示文件路径的字符串作为参数,返回该路径中文件名部分。 * 首先查找路径中最后一个斜杠或反斜杠的索引,若未找到则直接返回路径; * 若找到,则使用substring方法提取最后一个斜杠或反斜杠后面的字符串作为文件名并返回。 * @param path 文件路径 * @returns 文件全名(包含扩展名) */ export function getFileFullName(path: string): string { let index = path.lastIndexOf("/"); if (index === -1) { index = path.lastIndexOf("\\"); if (index === -1) { return path; } } return path.substring(index + 1); } /** * 获取文件名不包含扩展名 */ export function getFileNameWithoutExt(path: string): string { const fileName = getFileFullName(path); const index = fileName.lastIndexOf("."); if (index === -1) { return fileName; } return fileName.substring(0, index); } /** * 文件信息 */ export interface IFileInfo { /** 文件名(包含扩展名) */ fileName: string; /** * 文件名不带扩展名 */ fileNameNoExt: string; /** 文件扩展名 */ fileExtName: string; /** 路径仅包含文件夹 */ pathOnly: string; /** 完整路径 */ fullPath: string; } /** * 获取文件信息 * @param path 文件路径 * @param platform 平台名称,默认为"win32" * @returns 包含文件名、文件名不带扩展名、文件扩展名、路径仅包含文件夹、完整路径的对象 */ export function getFileInfo( path: string, platform: string = "win32" ): IFileInfo { const pathSaprator = platform === "win32" ? "\\" : "/"; let pathOnly: string; let fileName: string; let fileExtName: string; let fileNameNoExt: string; const pathIndex = path.lastIndexOf(pathSaprator); if (pathIndex === -1) { pathOnly = ""; fileName = path; } else { pathOnly = path.substring(0, pathIndex + 1); fileName = path.substring(pathIndex + 1); } const extIndex = fileName.lastIndexOf("."); if (extIndex === -1) { fileExtName = ""; fileNameNoExt = fileName; } else { fileExtName = fileName.substring(extIndex + 1); fileNameNoExt = fileName.substring(0, extIndex); } return { fileName, fileNameNoExt, fileExtName, fullPath: path, pathOnly, }; }