6 changed files with 63 additions and 0 deletions
@ -0,0 +1,2 @@ |
|||||
|
export * from "./slash"; |
||||
|
export * from "./sanitizeFileName"; |
@ -0,0 +1,13 @@ |
|||||
|
import { sanitizeFileName } from "../index"; |
||||
|
|
||||
|
describe("slash", async () => { |
||||
|
it("转换", async () => { |
||||
|
expect(sanitizeFileName("C:\\aa\\bb.txt")).toStrictEqual("C:\\aa\\bb.txt"); |
||||
|
}); |
||||
|
it("转换空格", async () => { |
||||
|
expect(sanitizeFileName("C:\\a a\\b b.txt")).toStrictEqual("C:\\a a\\b b.txt"); |
||||
|
}); |
||||
|
it("转换特殊字符", async () => { |
||||
|
expect(sanitizeFileName("C:\\a.*?a\\b b.txt")).toStrictEqual("C:\\a.__a\\b b.txt"); |
||||
|
}); |
||||
|
}); |
@ -0,0 +1,6 @@ |
|||||
|
--- |
||||
|
title: 清理无效文件名 |
||||
|
category: 工具 |
||||
|
--- |
||||
|
|
||||
|
sanitizeFileName |
@ -0,0 +1,20 @@ |
|||||
|
// https://github.com/rollup/rollup/blob/fec513270c6ac350072425cc045db367656c623b/src/utils/sanitizeFileName.ts
|
||||
|
|
||||
|
const INVALID_CHAR_REGEX = /[\u0000-\u001F"#$&*+,:;<=>?[\]^`{|}\u007F]/g; |
||||
|
const DRIVE_LETTER_REGEX = /^[a-z]:/i; |
||||
|
|
||||
|
/** |
||||
|
* 清理无效的文件名,防止使用非法字符串导致文件创建失败 |
||||
|
*/ |
||||
|
export function sanitizeFileName(name: string): string { |
||||
|
const match = DRIVE_LETTER_REGEX.exec(name); |
||||
|
const driveLetter = match ? match[0] : ""; |
||||
|
|
||||
|
return ( |
||||
|
driveLetter + |
||||
|
name |
||||
|
.slice(driveLetter.length) |
||||
|
.replace(INVALID_CHAR_REGEX, "_") |
||||
|
.replace(/(^|\/)_+(?=[^/]*$)/, "$1") |
||||
|
); |
||||
|
} |
@ -0,0 +1,13 @@ |
|||||
|
import { slash } from "../index"; |
||||
|
|
||||
|
describe("slash", async () => { |
||||
|
it("转换", async () => { |
||||
|
expect(slash("C:\\aa\\bb.txt")).toStrictEqual("C:/aa/bb.txt"); |
||||
|
}); |
||||
|
it("转换空格", async () => { |
||||
|
expect(slash("C:\\a a\\b b.txt")).toStrictEqual("C:/a a/b b.txt"); |
||||
|
}); |
||||
|
it("转换特殊字符", async () => { |
||||
|
expect(slash("C:\\a.*?a\\b b.txt")).toStrictEqual("C:/a.*?a/b b.txt"); |
||||
|
}); |
||||
|
}); |
@ -0,0 +1,9 @@ |
|||||
|
export function slash(path) { |
||||
|
const isExtendedLengthPath = path.startsWith("\\\\?\\"); |
||||
|
|
||||
|
if (isExtendedLengthPath) { |
||||
|
return path; |
||||
|
} |
||||
|
|
||||
|
return path.replace(/\\/g, "/"); |
||||
|
} |
Loading…
Reference in new issue