0
0
NodejsHow-ToBeginner · 3 min read

How to Get File Extension in Node.js Using path.extname

In Node.js, you can get a file extension using the path.extname() method from the built-in path module. It returns the extension including the dot, like .txt or .js.
📐

Syntax

The path.extname(path) method takes a file path string and returns the extension part of the file name, including the leading dot.

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

const extension = path.extname('filename.txt');
console.log(extension); // Outputs: .txt
Output
.txt
💻

Example

This example shows how to get the extension from different file names and paths using path.extname(). It prints the extension or an empty string if there is none.

javascript
const path = require('path');

const files = [
  'document.pdf',
  'archive.tar.gz',
  'image',
  '/folder/music.mp3',
  'notes.txt'
];

files.forEach(file => {
  const ext = path.extname(file);
  console.log(`File: ${file} => Extension: '${ext}'`);
});
Output
File: document.pdf => Extension: '.pdf' File: archive.tar.gz => Extension: '.gz' File: image => Extension: '' File: /folder/music.mp3 => Extension: '.mp3' File: notes.txt => Extension: '.txt'
⚠️

Common Pitfalls

One common mistake is expecting path.extname() to return multiple extensions like .tar.gz. It only returns the last extension part (e.g., .gz).

Also, if the file name has no extension, it returns an empty string, so always check for that before using the result.

javascript
const path = require('path');

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

// Right: handle multi-part extensions manually if needed
const fileName = 'archive.tar.gz';
const parts = fileName.split('.');
const multiPartExt = parts.length > 2 ? '.' + parts.slice(1).join('.') : path.extname(fileName);
console.log(multiPartExt); // Outputs: .tar.gz
Output
.gz .tar.gz
📊

Quick Reference

Remember these tips when using path.extname():

  • Returns extension with leading dot (e.g., .js).
  • Returns empty string if no extension.
  • Only returns last extension part for multi-dot filenames.
  • Use string methods if you need full multi-part extensions.

Key Takeaways

Use Node.js built-in path.extname() to get a file's extension including the dot.
path.extname() returns only the last extension part for files with multiple dots.
If a file has no extension, path.extname() returns an empty string.
Check the returned extension before using it to avoid errors.
For full multi-part extensions, use string splitting methods manually.