File size: 1,720 Bytes
3a1d71c |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 |
export function isAbsolute (path: string): boolean {
return /^(?:\/|[a-z]:)/i.test(normalize(path))
}
export function normalize (path: string): string {
if (!path) {
return ''
}
// 将路径分隔符替换为斜杠
path = path.replace(/\\/g, '/')
// 将多个连续斜杠替换为一个
path = path.replace(/\/+/g, '/')
// 处理 .. 和 .
const parts = path.split('/')
const newParts = []
for (let i = 0; i < parts.length; i++) {
const part = parts[i]
if (part === '..') {
newParts.pop()
} else if (part !== '' && part !== '.') {
newParts.push(part)
}
}
// 重新组合路径
const result = newParts.join('/')
const startWithSlash = path.startsWith('/')
if (startWithSlash) {
return '/' + result
} else {
return result
}
}
export function join (...paths: string[]): string {
if (!paths.length) {
return ''
}
// 将所有路径组合成一个字符串
let result = paths.join('/')
// 规范化路径
result = normalize(result)
// 如果原始路径以斜杠结尾,则结果也以斜杠结尾
const endsWithSlash = paths[paths.length - 1].endsWith('/')
if (endsWithSlash && !result.endsWith('/')) {
return result + '/'
} else {
return result
}
}
export const normalizeRelativePathToAbsolute = (relativePath: string, cwd: string) => {
const absolutePath = isAbsolute(relativePath)
? relativePath
: normalize(join(cwd, relativePath))
return normalize(absolutePath)
}
export const splitPath = (path: string) => {
path = normalize(path)
const frags = path.split('/').filter(v => v)
if (frags[0].endsWith(':')) {
frags[0] = frags[0] + '/'// 分割完是c: -> c:/
}
return frags
}
|