sanitize-filename

Sanitize string for use as filename

sanitize-filename

Sanitize a string to be safe for use as a filename in Windows and Unix file systems by stripping control characters, restricted characters \/:*?"<>|, and the reserved filenames, . and ...

// Some string that may be unsafe as a filesystem filename 
var UNSAFE_FILENAME = "h*ello:/world?\u0000";
 
// Sanitize the unsafe filename to be safe for use as a filename 
var sanitize = require("sanitize-filename"),
    filename = sanitize(UNSAFE_FILENAME);
 
// Create a file using the safe filename 
require("fs").createWriteStream(filename).end();

Note that two unique inputs can result in the same output. For example, sanitize("file?") and sanitize("file*") will both return "file".

Note that the return value can be an empty string. For example, sanitize("><") will return "". To avoid this, use a default value (e.g., sanitize("><") || "default") or options.replacement.

Sanitize the input string, filename, removing or replacing unsafe characters. The options.replacement can be a string to replace unsafe characters with.

npm install sanitize-filename