-
Notifications
You must be signed in to change notification settings - Fork 30
Expand file tree
/
Copy path01-sanitize-filename.js
More file actions
32 lines (28 loc) · 1019 Bytes
/
01-sanitize-filename.js
File metadata and controls
32 lines (28 loc) · 1019 Bytes
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
class FileNameSanitizer {
// Modified from https://github.com/parshap/node-sanitize-filename
_truncate(str, nchars) {
let enc = new TextEncoder();
let dec = new TextDecoder('utf-8');
let uint8 = enc.encode(str)
let section = uint8.slice(0,nchars)
let result = dec.decode(section);
return result.replace(/\uFFFD/g, '');
}
sanitize(input, replacement) {
const illegalRe = /[\/\?<>\\:\*\|"]/g;
const controlRe = /[\x00-\x1f\x80-\x9f]/g;
const reservedRe = /^\.+$/;
const windowsReservedRe = /^(con|prn|aux|nul|com[0-9]|lpt[0-9])(\..*)?$/i;
const windowsTrailingRe = /[\. ]+$/;
if (typeof input !== 'string') {
throw new Error('Input must be string');
}
const sanitized = input
.replace(illegalRe, replacement)
.replace(controlRe, replacement)
.replace(reservedRe, replacement)
.replace(windowsReservedRe, replacement)
.replace(windowsTrailingRe, replacement);
return this._truncate(sanitized, 255);
}
}