The path.extname() method is used to get the extension portion of a file path. The extension string returned from the last occurrence of a period (.) in the path to the end of the path string. If there are no periods in the file path, then an empty string is returned.
Syntax:
path.extname( path )
Parameters: This method accepts single parameter path which holds the file path that would be used to extract the extension.
Return Value: It returns a string with the extension portion of the path. It throws a TypeError if this parameter is not a string value.
Below examples illustrate the path.extname() method in node.js:
Example 1:
const path = require( 'path' );
path1 = path.extname( "hello.txt" );
console.log(path1)
path2 = path.extname( "readme.md" );
console.log(path2)
path3 = path.extname( "fileDump" )
console.log(path3)
path4 = path.extname( "example." )
console.log(path4)
path5 = path.extname( "readme.md.txt" )
console.log(path5)
path6 = path.extname(__filename)
console.log(path6)
|
Output:
.txt
.md
.
.txt
.js
Example 2:
const path = require( 'path' );
paths_array = [
"/home/user/website/index.html" ,
"/home/user/website/style.css" ,
"/home/user/website/bootstrap.css" ,
"/home/user/website/main.js" ,
"/home/user/website/contact_us.html" ,
"/home/user/website/services.html" ,
]
paths_array.forEach(filePath => {
if (path.extname(filePath) == ".html" )
console.log(filePath);
});
|
Output:
/home/user/website/index.html
/home/user/website/contact_us.html
/home/user/website/services.html
Reference: https://nodejs.org/api/path.html#path_path_extname_path