N Kaushik

How to find the extension of a file in Nodejs or express server

June 30, 2021

How to find the extension of a file in Nodejs or express server:

This problem I faced recently. This is pretty easy if you are familiar with the path module. path module provides one method called extname() that we can use to find out the extension of a file.

In this post, I will show you how to do that with one small example.

A little bit on path module:

path module provides different utility methods those can be used with file and directory paths. It is an inbuilt module and we don’t need any third party library to install it.

This module can be accessed as like below:

const path = require('path');

extname() method:

extname method is used to get the extension for a file name in nodejs. We need to pass the path of a file as the argument to this method and it returns the extension for that file.

It is defined as below:

path.extname(file_path)

Arguments:

It takes the file path, file_path as its argument. It returns the extension of the file at that path, i.e. a string.

Exception:

It throws TypeError if the argument is not a string.

Example program:

Note that, it doesn’t check if the file actually exists on that path or not. Let’s take a look at the below program:

const path = require('path')

console.log(path.extname('./image.png'))
console.log(path.extname('./image2.png'))
console.log(path.extname('./example.js'))
console.log(path.extname('./image'))
console.log(path.extname('./image.ext.js.png.jpg'))

If you run this, it will print the below output:

.png
.png
.js

.jpg

If the file doesn’t have any extension, it returns one empty string.

Conclusion:

In this post, we learned how to use extname() method with examples. path module provides different useful methods that you can check in the nodejs doc. If you love this post, please do subscribe to my newsletter :)


Subscribe to my Newsletter

© 2021, nkaushik