How to get a file extension in Node.js

When working inside a node environment, working with file paths and directories is a common occurrence. As such, the desire to get as much detail about the file types is very important.

So, how can you get a file extension in Node.js? This is easily achieved by using Node.js’s native path library.

It allows us to use the method .extName() which returns the extension of the path, after the last occurrence of the . character.

This is very handy, as it allows us to do the following in our Node.js files:

var path = require('path')

console.log(path.extname('index.html'))
// '.html'

Be aware that this method doesn’t account for two occurrences of . in an extension name. So if we have a file name like filename.css.gz we can get the extension by using the following:

const filename = 'filename.css.gz'
const ext = filename.substring(filename.indexOf('.')+1); 
//ext = 'with.long.extension

Additionally,  if we want to get the file extension of a URL path with a query parameter. This is also straightforward using Node’s  native URL package:

const Url = require('url');
const Path = require('path');
const url = 'http://test-image.jpg?querystring=test';
const result = Path.extname(Url.parse(url).pathname); // '.jpg'

I hope this helped. 

Proudly published with Gatsby