path.extname() function in Node.js29 Apr 2025 | 4 min read In this article, we will discuss the path.extname() function in Node.js with their syntax, parameters, and examples. What is the path.extname() function in Node.js?The path.extname() method in Node.js is part of the built-in path module. It obtains the extension of the file from the given file path. This component of the string begins with the last instance of the dot (.), which includes the dot itself. It is known as the file name portion. A file's type is determined by its extension using these functions. It will produce a string containing the leading dot if there is an extension (.txt for example); otherwise, it will output an empty string. This feature facilitates operations like file uploads, such as verifying file extensions or recognizing file kinds. It ignores query strings and URL fragments and supports both Unix (/) and Windows (\) path formats. Path.extname('file.tar.gz') returns .gz. It is simple to use and perfect for applications that require file processing or MIME type recognition. Syntax:It has the following syntax: Parameters:
Return Value:This string contains the file extension and the leading dot (.). If there is no file extension or the last character of the path is a dot (.), an empty string ("") is returned. Key points:
Example 1:Let us take an example to illustrate the path.extname() function in Node.js. Output: .js .json .png?size=large .gz Explanation:
Main points:
Example 2:Let us take another example to illustrate the path.extname() function in Node.js. Output: JavaScript Files: [ 'script.js' ] Image Files: [ 'photo.jpg' ] PDF Files: [ 'document.pdf' ] Files Without Extension: [ 'README', '.gitignore' ] Explanation:
Conclusion:In conclusion, Node.js's path.extname() method offers a powerful solution when working with file extensions. Because it helps extract the extension from a specific file path, it is very useful in scenarios like file validation, classification, and MIME type identification. The function supports both Unix and Windows file path formats and gracefully handles edge cases, including hidden files, files without an extension, and URLs with query strings. By utilizing its features, developers may manage file-related operations efficiently, enhancing control and reliability in applications that handle or process a range of file types. Next TopicOs-userinfo-options-function-in-nodejs |
We request you to subscribe our newsletter for upcoming updates.

We provides tutorials and interview questions of all technology like java tutorial, android, java frameworks
G-13, 2nd Floor, Sec-3, Noida, UP, 201301, India