This guide will explain the “path.basename()” method in Node.js.
How Does path.basename() Work in Node.js?
The “basename()” is the built-in method of the “path” module that retrieves the file name part from the specified path. Its working relies on its basic syntax which is mentioned below:
According to the above syntax, the “basename()” method works on the following parameters:
- path: It denotes the file path.
- extension: It is an optional parameter that would be removed while retrieving the file name portion from the path.
Now, use the above-defined method practically.
Example 1: Applying “path.basename()” Method For Windows Files
This example uses the “path.basename()” method for Windows Files:
var filename = path.basename('C:\\users\\Lenovo\\File\\Hello.html');
console.log(filename);
In the above code lines:
- Firstly, the “require()” method includes the “path” module in the Node.js project.
- Next, the “filename” variable applies the “basename()” method that passes the path of a file as its argument.
- Lastly, the “console.log()” method displays the output of the “basename()” method stored in the “filename” variable on the console.
Output
Execute the “.js” file with the help of given command:
It can be observed that the output displays the file name along with its extension:
Example 2: Applying “path.basename()” Method For UNIX Files
This example applies the “path.basename()” method for the files of the UNIX operating system:
var filename = path.basename('/users/admin/file.js', ".js");
console.log(filename);
In the above code lines:
- The “basename()” method takes the file path and retrieves the file name from it without its extension because of the specified extension parameter.
- The “console.log()” method displays the output of the “basename()” method.
Output
Initiate the “.js” file:
It can be seen that the output shows the file name without its extension:
That’s all about the working of the “path.basename()” method in Node.js.
Conclusion
In Node.js, the “path.basename()” method retrieves the file name part from the specified path. This method performs this task by passing the particular file path as its mandatory parameter. It returns the file name along with its extension. If the user wants to remove the file extension then use the optional parameter “extension” that removes the file extension while retrieving it from the specified path. This guide has practically explained the “path.basename()” method in Node.js.