The path.extname() method in Node.js is used to retrieve the extension of a file from a given path. It helps developers identify file formats and perform extension-based operations when working with files and directories.
- Commonly used to validate or filter files based on their type.
- Useful when handling uploads, file processing, or generating file-specific logic.
- It helps in file validation, filtering, and path handling tasks.
Syntax:
path.extname(path)where,
- path: The file path from which the extension needs to be extracted.
Return Value: Returns an empty string if the specified path does not contain a file extension.
Example 1:
// 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:
// 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
Use Cases of path.extname() Method
Use Cases of path.extname() Method
- File Type Validation: Check whether a file has an allowed extension before processing or uploading it.
- File Filtering: Display or process only specific file types, such as
.jpg,.png, or.pdf. - Conditional File Handling: Apply different operations based on the file extension, such as opening images, documents, or videos with different logic.