Open In App

How to Sanitize Your File Names using the ‘sanitize-filename’ npm Package ?

The ‘sanitize-filename’ is a very important and useful npm package that can be used to sanitize file names by removing all the unwanted characters or white spaces from the file name and making it a proper file name according to the specific file system or operating system.

sanitize() Function: It is a very important function in this module or package. It takes file name in strings as input and returns the file name in a proper format that can be safely used as a file name.



Applications of sanitize-filename: Here are a few examples of when and where you might use this package:

 



How to sanitize your file names using the ‘sanitize-filename’ npm package?

Installation: To use this package, first, we have to install it. We can install this package using the command given below. Give the same command in the terminal and this package will get installed. After successful installation, a JSON file will be added to the directory which contains all the details of the installed packages.

$ npm install sanitize-filename

Installation

Use the package: After installation, we can use the module easily in our JavaScript application project. Firstly, we have to import the package using the require function and after successfully importing it, we can start implementing it. Pass the file name as a string to the sanitize function and it generates a sanitized and proper file name as output.




const sanitize = require('sanitize-filename');
  
// Input string
const fileName = 'My/File:Name.txt';
  
// Sanitize function
const sanitizedFileName = sanitize(fileName);
  
console.log(sanitizedFileName); // Output

Run the code: After successfully writing the code, we have to run the javascript code file using the command given below :

$ node index.js

where index.js is the javascript file name.

Output:

Output

Conclusion: In conclusion, ‘sanitize-filename‘ is a valuable package for developers who need to ensure that file names comply with various file systems and applications and are free from potential issues. This package provides a straightforward and efficient method for sanitizing file names by removing potentially harmful or invalid characters, like slashes, colons, and quotes. It also enables the replacement of these characters with a safe alternative, such as an underscore or hyphen.

Article Tags :