# How to get the file extension in Node.js

By Atta Ur Rehman Shah (https://attacomsian.com/about). Published Jun 24, 2021, updated Oct 3, 2022. Topics: Node.js.
Canonical URL: https://attacomsian.com/blog/nodejs-get-file-extension

> A quick guide to learn how to get the file extension using Node.js.

To get the file extension in a Node.js application, you can use the `extname()` method from the `path` built-in module.

Here is an example:

```javascript
const path = require('path')

path.extname('index.html') // .html
path.extname('name.png')   // .png
path.extname('name.of.months.pdf') // .pdf
```

The `extname()` method returns the given path extension from the last occurrence of the `.` (period) character to the end of the string in the last part of the path.

If there is no `.` in the last part of the path, or if the path starts with `.` and is the only `.` character in the path, an empty string is returned:

```javascript
path.extname('index.') // .

path.extname('index') // '' (empty string)

path.extname('.index')   // '' (empty string)

path.extname('.index.md') // .md
```

If the path provided is not a string, a `TypeError` is thrown.
