How to Get a File Extension in Node.js
Last updated on September 29, 2022

To get the extension of a file in Node.js, we can use the extname()
method from the path
module.
For example:
const path = require('path');
path.extname('style.css') // .css
path.extname('image.png') // .png
path.extname('prettier.config.js') // .js
11 Amazing New Features in ES13

Get up to speed with all the latest features added in ECMAScript 13 to modernize your JavaScript with shorter and more expressive code.
The extname()
method
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, extname()
returns an empty string.
path.extname('index.'); // .
path.extname('index'); // '' (empty string)
path.extname('.index'); // '' (empty string)
path.extname('.index.html'); // .html
If the path is not a string, extname()
throws a TypeError
.
const path = require('path');
// ❌ TypeError: Received type number instead of string
path.extname(123);
// ❌ TypeError: Received type boolean instead of string
path.extname(false);
// ❌ TypeError: Received URL instance instead of string
path.extname(new URL('https://example.com/file.txt'));
// ✅ Received type of string
path.extname('package.json'); // .json
Every Crazy Thing JavaScript Does

Avoid painful bugs and save valuable time with Every Crazy Thing JavaScript Does, a captivating guide to the subtle caveats and lesser-known parts of JavaScript.