Sanitize string for use as filename
Clone or download
Fetching latest commit…
Cannot retrieve the latest commit at this time.
Failed to load latest commit information.
vendor Update dependencies Sep 25, 2015
.npmignore Add vendor directory to npmignore Sep 29, 2016
.zuul.yml Browser testing using zuul and Sauce Labs Nov 6, 2015
AUTHORS Changelog Mar 19, 2015 License: WTFPL or ISC Sep 25, 2015 Add documentation for replacement functions (#39) Jul 5, 2017
index.js Make windows-trailing character tests pass Apr 28, 2016
package.json chore(package): update browserify to version 14.0.0 (#33) May 4, 2017
test.js Add tests for trailing periods/spaces Apr 28, 2016

sanitize-filename build status

Sanitize a string to be safe for use as a filename by removing directory paths and invalid characters.


npm: sanitize-filename

npm install sanitize-filename


var sanitize = require("sanitize-filename");

// Some string that may be unsafe or invalid as a filename
var UNSAFE_USER_INPUT = "~/.\u0000ssh/authorized_keys";

// Sanitize the string to be safe for use as a filename.
var filename = sanitize(UNSAFE_USER_INPUT);
// -> "~.sshauthorized_keys"


sanitize-filename removes the following:

  • Control characters (0x000x1f and 0x800x9f)
  • 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, and LPT9)

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.

Empty String "" Result

An empty string "" can be returned. For example:

var sanitize = require("sanitize-filename");
// -> ""

Non-unique Filenames

Two different inputs can return the same value. For example:

var sanitize = require("sanitize-filename");
// -> "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.


sanitize(inputString, [options])

Sanitize inputString by removing or replacing invalid characters.


  • 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. See String.prototype.replace for more info.