How to Get a File Extension in Node.js

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

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

// ❌ TypeError: Received type boolean instead of string

// ❌ TypeError: Received URL instance instead of string
path.extname(new URL(''));

// ✅ Received type of string
path.extname('package.json'); // .json

Every Crazy Thing JavaScript Does

A captivating guide to the subtle caveats and lesser-known parts of JavaScript.

Every Crazy Thing JavaScript Does

Sign up and receive a free copy immediately.

Leave a Comment

Your email address will not be published. Required fields are marked *