How to Get a File Extension in Node.js

Last updated on September 29, 2022
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
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
Coding Beauty Assistant logo

Try Coding Beauty AI Assistant for VS Code

Meet the new intelligent assistant: tailored to optimize your work efficiency with lightning-fast code completions, intuitive AI chat + web search, reliable human expert help, and more.

See also