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:

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 extension of the given path 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 it is the only . character in the path, an empty string is returned:

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.

✌️ Like this article? Follow me on Twitter and LinkedIn. You can also subscribe to RSS Feed.