The
path.basename() method is used to get the filename portion of a path to the file. The trailing directory separators are ignored when using this method.
Syntax:
path.basename( path, extension )
Parameters: This method accepts two parameters as mentioned above and described below:
- path: It is the file path that would be used to extract the filename.
- extension: It is an optional file extension that would be removed from the returned string.
Return Value: It returns a string with the filename portion of the path. It throws an error if the path or the extension parameters are not string values.
Below programs illustrate the
path.basename() method in node.js:
Example 1: Using UNIX file paths
Output:
index.txt
index
Example 2: Using Windows file paths
Output:
index.html
index
Reference: https://nodejs.org/docs/latest-v11.x/api/path.html#path_path_basename_path_ext