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
// Node.js program to demonstrate the // path.basename() method // Import the path module const path = require('path'); path1 = path.basename('/home/user/bash/index.txt'); console.log(path1) // Using the extension parameter path2 = path.basename('/home/user/bash/index.txt', '.txt'); console.log(path2) |
Output:
index.txt index
Example 2: Using Windows file paths
// Node.js program to demonstrate the // path.basename() method // Import the path module const path = require('path'); path1 = path.basename('C:\\users\\bash\\index.html'); console.log(path1) // Using the extension parameter path2 = path.basename('C:\\users\\bash\\index.html', '.html'); console.log(path2) |
Output:
index.html index
Reference: https://nodejs.org/docs/latest-v11.x/api/path.html#path_path_basename_path_ext
Recommended Posts:
- Nodejs | Automatic restart NodeJs server with nodemon
- Nodejs console.timeLog() Method
- Nodejs - Connect MongoDB with Node app using MongooseJS
- Cowsay in Nodejs using Requests library
- Nodejs | Web Crawling using Cheerio
- Web-Socket in NodeJS
- Signup Form Using Nodejs and MongoDB
- Dockerizing a simple Nodejs app
- Nodejs | DNS
- Encrypting Data in NodeJS
- Difference between NodeJS and AngularJS
- Nodejs | Jimp
- Nodejs – Connect Mysql with Node app
- Nodejs | DNS | setServers()
- NodeJS | Building simple REST API in express
- NodeJs - Handling invalid routes
- Nodejs | authentication using Passportjs and passport-local-mongoose
- Nodejs | GM charcoal() Function
- Nodejs | GM blur() Function
- Nodejs | GM sharpen() Function
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.

