ez-common-ts/src/commons/file-util.ts

106 lines
2.6 KiB
TypeScript
Raw Normal View History

2023-11-12 22:00:29 +08:00
/**
*
* @param fileName
* @returns
*/
export function getFileExt(fileName: string): string {
const index = fileName.lastIndexOf(".");
if (index === -1) {
return "";
}
return fileName.substring(index + 1);
}
/**
2023-11-14 15:52:35 +08:00
*
2023-11-12 22:00:29 +08:00
*
*
* 使substring方法提取最后一个斜杠或反斜杠后面的字符串作为文件名并返回
* @param path
2023-11-14 15:52:35 +08:00
* @returns
2023-11-12 22:00:29 +08:00
*/
2023-11-14 15:52:35 +08:00
export function getFileFullName(path: string): string {
2023-11-12 22:00:29 +08:00
let index = path.lastIndexOf("/");
if (index === -1) {
index = path.lastIndexOf("\\");
if (index === -1) {
return path;
}
}
return path.substring(index + 1);
}
2023-11-14 15:52:35 +08:00
/**
*
*/
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,
};
}