Node.js path.extname() Method (original) (raw)

Last Updated : 13 Oct, 2021

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:

javascript `

// Node.js program to demonstrate the
// path.extname() method

// Import the path module const path = require('path');

path1 = path.extname("hello.txt"); console.log(path1)

path2 = path.extname("readme.md"); console.log(path2)

// File with no extension // Returns empty string path3 = path.extname("fileDump") console.log(path3)

// File with blank extension // Return only the period path4 = path.extname("example.") console.log(path4)

path5 = path.extname("readme.md.txt") console.log(path5)

// Extension name of the current script path6 = path.extname(__filename) console.log(path6)

`

Output:

.txt .md

. .txt .js

Example 2:

javascript `

// Node.js program to demonstrate the
// path.extname() method

// Import the path module const path = require('path');

// Comparing extensions from a // list of file paths 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