0
0
NodejsHow-ToBeginner · 3 min read

How to Use path.extname in Node.js to Get File Extensions

In Node.js, use path.extname(path) to get the file extension from a file path string. It returns the extension including the dot, like .txt or .js. You first import path from Node.js core modules before using it.
📐

Syntax

The path.extname(path) method takes a single string argument path which is the file path or file name. It returns the extension of the file including the leading dot (.), or an empty string if there is no extension.

  • path: A string representing the file path or file name.
  • Returns: A string with the file extension including the dot, or an empty string if none.
javascript
const path = require('path');

const ext = path.extname('/folder/file.txt');
console.log(ext); // Outputs: .txt
Output
.txt
💻

Example

This example shows how to use path.extname to get extensions from different file paths. It prints the extension for each file path given.

javascript
import path from 'path';

const files = [
  '/home/user/document.pdf',
  'archive.tar.gz',
  'image',
  '.hiddenfile',
  'script.js'
];

files.forEach(file => {
  console.log(`${file} -> ${path.extname(file)}`);
});
Output
/home/user/document.pdf -> .pdf archive.tar.gz -> .gz image -> .hiddenfile -> script.js -> .js
⚠️

Common Pitfalls

Common mistakes include expecting path.extname to return multiple extensions (like .tar.gz) or to work on URLs. It only returns the last extension part after the last dot. Also, it returns an empty string if the file has no extension or starts with a dot but has no extension.

Wrong usage example:

const ext = path.extname('archive.tar.gz');
console.log(ext); // Outputs: .gz (not .tar.gz)

Correct understanding is to handle multiple extensions manually if needed.

javascript
import path from 'path';

// Wrong assumption: expecting full multi-part extension
const file = 'archive.tar.gz';
console.log(path.extname(file)); // Outputs: .gz

// To get full extension, custom code is needed
const fullExt = file.split('.').slice(1).join('.');
console.log(`Full extension: .${fullExt}`); // Outputs: .tar.gz
Output
.gz Full extension: .tar.gz
📊

Quick Reference

Remember these key points about path.extname:

  • Returns the last extension including the dot.
  • Returns empty string if no extension.
  • Works with file paths and file names.
  • Does not parse URLs or multiple extensions fully.

Key Takeaways

Use path.extname(path) to get the file extension including the dot.
It returns only the last extension part, not multiple extensions like .tar.gz.
Returns an empty string if the file has no extension.
Import path from Node.js core modules before using.
For complex extension parsing, write custom logic beyond path.extname.