From 8755ea374b055a0858570e2c7e464d4667e1e503 Mon Sep 17 00:00:00 2001 From: zhujingjing Date: Sun, 12 Nov 2023 22:00:29 +0800 Subject: [PATCH] add file-util --- lib/commons/file-util.d.ts | 15 +++++++++++++++ src/commons/file-util.ts | 31 +++++++++++++++++++++++++++++++ 2 files changed, 46 insertions(+) create mode 100644 lib/commons/file-util.d.ts create mode 100644 src/commons/file-util.ts diff --git a/lib/commons/file-util.d.ts b/lib/commons/file-util.d.ts new file mode 100644 index 0000000..7eae994 --- /dev/null +++ b/lib/commons/file-util.d.ts @@ -0,0 +1,15 @@ +/** + * 获取文件的后缀名 + * @param fileName 文件名 + * @returns 文件后缀名 + */ +export declare function getFileExt(fileName: string): string; +/** + * 获取文件名 + * 该函数接收一个表示文件路径的字符串作为参数,返回该路径中文件名部分。 + * 首先查找路径中最后一个斜杠或反斜杠的索引,若未找到则直接返回路径; + * 若找到,则使用substring方法提取最后一个斜杠或反斜杠后面的字符串作为文件名并返回。 + * @param path 文件路径 + * @returns 文件名 + */ +export declare function getFileName(path: string): string; diff --git a/src/commons/file-util.ts b/src/commons/file-util.ts new file mode 100644 index 0000000..bc916a6 --- /dev/null +++ b/src/commons/file-util.ts @@ -0,0 +1,31 @@ +/** + * 获取文件的后缀名 + * @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 getFileName(path: string): string { + let index = path.lastIndexOf("/"); + if (index === -1) { + index = path.lastIndexOf("\\"); + if (index === -1) { + return path; + } + } + return path.substring(index + 1); +}