/**
|
* 跨平台路径处理工具函数
|
*/
|
|
/**
|
* 从路径中提取文件名(兼容Windows和Unix系统)
|
* @param {string} filePath - 文件路径
|
* @returns {string} 文件名
|
*/
|
export function getFileName(filePath) {
|
if (!filePath) return '';
|
// 使用正则表达式匹配Windows的反斜杠或Unix的斜杠
|
return filePath.split(/[/\\]/).pop() || '';
|
}
|
|
/**
|
* 从路径中提取目录路径(兼容Windows和Unix系统)
|
* @param {string} filePath - 文件路径
|
* @returns {string} 目录路径
|
*/
|
export function getDirectoryPath(filePath) {
|
if (!filePath) return '';
|
const parts = filePath.split(/[/\\]/);
|
parts.pop(); // 移除文件名
|
return parts.join('/');
|
}
|
|
/**
|
* 规范化路径(统一使用正斜杠)
|
* @param {string} filePath - 文件路径
|
* @returns {string} 规范化后的路径
|
*/
|
export function normalizePath(filePath) {
|
if (!filePath) return '';
|
// 将所有反斜杠替换为正斜杠
|
return filePath.replace(/\\/g, '/');
|
}
|
|
/**
|
* 连接路径片段(兼容Windows和Unix系统)
|
* @param {...string} segments - 路径片段
|
* @returns {string} 连接后的路径
|
*/
|
export function joinPath(...segments) {
|
const filtered = segments.filter(segment => segment && typeof segment === 'string');
|
if (filtered.length === 0) return '';
|
|
// 规范化每个片段并连接
|
return filtered
|
.map((segment, index) => {
|
// 移除开头和结尾的分隔符(除了第一个片段的开头)
|
let normalized = segment.replace(/[/\\]+$/, '');
|
if (index > 0) {
|
normalized = normalized.replace(/^[/\\]+/, '');
|
}
|
return normalized;
|
})
|
.join('/');
|
}
|
|
/**
|
* 获取文件扩展名
|
* @param {string} filePath - 文件路径
|
* @returns {string} 文件扩展名(包含点号)
|
*/
|
export function getFileExtension(filePath) {
|
if (!filePath) return '';
|
const fileName = getFileName(filePath);
|
const lastDotIndex = fileName.lastIndexOf('.');
|
if (lastDotIndex === -1 || lastDotIndex === 0) return '';
|
return fileName.substring(lastDotIndex);
|
}
|
|
/**
|
* 获取不带扩展名的文件名
|
* @param {string} filePath - 文件路径
|
* @returns {string} 不带扩展名的文件名
|
*/
|
export function getFileNameWithoutExtension(filePath) {
|
if (!filePath) return '';
|
const fileName = getFileName(filePath);
|
const lastDotIndex = fileName.lastIndexOf('.');
|
if (lastDotIndex === -1 || lastDotIndex === 0) return fileName;
|
return fileName.substring(0, lastDotIndex);
|
}
|
|
/**
|
* 判断是否为绝对路径
|
* @param {string} filePath - 文件路径
|
* @returns {boolean} 是否为绝对路径
|
*/
|
export function isAbsolutePath(filePath) {
|
if (!filePath) return false;
|
// Windows绝对路径: C:\ 或 C:/
|
// Unix绝对路径: /
|
return /^([a-zA-Z]:[\\/]|\/|\\\\)/.test(filePath);
|
}
|
|
/**
|
* 将相对路径转换为绝对路径
|
* @param {string} basePath - 基础路径
|
* @param {string} relativePath - 相对路径
|
* @returns {string} 绝对路径
|
*/
|
export function resolveRelativePath(basePath, relativePath) {
|
if (!relativePath) return basePath;
|
if (isAbsolutePath(relativePath)) return relativePath;
|
|
return joinPath(basePath, relativePath);
|
}
|