How to get the file extension in Node.js
By Flavio Copes
Learn how to get a file extension in Node.js using the built-in path module and its extname() method, which returns values like .png or .jpg from a file name.
To get the file extension in Node.js, use the built-in path module and its extname() method. It returns the extension with the leading dot, like .png or .jpg.
I had the need to find the extension of a file.
I had the name of the file, in my case an image, and wanted to get the extension (.jpg, .png..).
To do this, you can use the path built-in module and its extname() method:
const path = require('path')
path.extname('picture.png') //.png
path.extname('picture.of.a.dog.png') //.png
path.extname('picture.of.a.dog.jpg') //.jpg
path.extname('picture.of.a.dog.jpeg') //.jpeg
extname() returns everything from the last dot to the end of the string. It works on full paths too, not just file names:
path.extname('/Users/flavio/photos/picture.png') //.png
The edge cases
A few inputs return something you might not expect:
path.extname('notes') //''
path.extname('.gitignore') //''
path.extname('archive.tar.gz') //'.gz'
path.extname('report.') //'.'
No dot means no extension, so you get an empty string.
Dotfiles like .gitignore also return an empty string. The leading dot marks a hidden file on Unix systems, it’s not an extension, and extname() knows that.
Compound extensions like .tar.gz only give you the last part. If you need the full .tar.gz, you have to handle that case yourself.
Removing the dot
If you want png instead of .png, cut off the first character:
path.extname('picture.png').slice(1) //'png'
Why not just split on the dot?
You’ll see this approach around:
'picture.png'.split('.').pop() //'png'
It works on that input, then breaks on the edge cases. On 'notes' it returns 'notes', the whole file name. On '.gitignore' it returns 'gitignore', treating a hidden file as an extension.
If you then check the “extension” against a list of allowed image formats, a file with no extension slips through as its own name. The fix is to not reinvent this: extname() already handles the edge cases correctly.
Related posts about node: