sanitize-filename-truncate
Sanitize a string to be safe for use as a filename by removing directory paths and invalid characters. With the ability to truncate to variable and replace white space
Install
npm: sanitize-filename-truncate
npm install sanitize-filename-truncate
Example
import sanitize from "sanitize-filename-truncate";
// Some string that may be unsafe or invalid as a filename
const UNSAFE_USER_INPUT = "~/.\u0000ssh/authorized_keys";
// Sanitize the string to be safe for use as a filename.
const filename = sanitize(UNSAFE_USER_INPUT);
// -> "~.sshauthorized_keys"
sanitize(UNSAFE_USER_INPUT, { truncate: 10, convertWhiteSpace: "_" });
Details
sanitize-filename removes the following:
-
Control characters (
0x00
–0x1f
and0x80
–0x9f
) -
Reserved characters (
/
,?
,<
,>
,\
,:
,*
,|
, and"
) - Unix reserved filenames (
.
and..
) - Trailing periods and spaces (for Windows)
- Windows reserved filenames (
CON
,PRN
,AUX
,NUL
,COM1
,COM2
,COM3
,COM4
,COM5
,COM6
,COM7
,COM8
,COM9
,LPT1
,LPT2
,LPT3
,LPT4
,LPT5
,LPT6
,LPT7
,LPT8
, andLPT9
)
The resulting string is truncated to 255 bytes in length. The string will not contain any directory paths and will be safe to use as a filename.
""
Result
Empty String An empty string ""
can be returned. For example:
var sanitize = require("sanitize-filename");
sanitize("..");
// -> ""
Non-unique Filenames
Two different inputs can return the same value. For example:
var sanitize = require("sanitize-filename");
sanitize("file?");
// -> "file"
sanitize("*file*");
// -> "file"
File Systems
Sanitized filenames will be safe for use on modern Windows, OS X, and Unix file systems (NTFS
, ext
, etc.).
FAT
8.3 filenames are not supported.
Test Your File System
The test program will use various strings (including the Big List of Naughty Strings) to create files in the working directory. Run npm test
to run tests against your file system.
API
sanitize(inputString, [options])
Sanitize inputString
by removing or replacing invalid characters.
Options:
-
options.replacement
: optional, string/function, default:""
. If passed as a string, it's used as the replacement for invalid characters. If passed as a function, the function will be called with the invalid characters and it's return value will be used as the replacement. SeeString.prototype.replace
for more info. -
options.truncateNumber
: optional, integer, default:""
. If passed truncates returned string -
options.convertWhiteSpace
: optional, string/function, default:""
. If passed as a string, it's used as the replacement for whitespace. If passed as a function, the function will be called with whitespace and it's return value will be used as the replacement.