path.extname
- Node.js course
- Beginner
- Lesson 110/116
- 5 min
Learn to get the file extension with path.extname.
What is path.extname?
path.extname returns the extension of a path; the dot is included. If there is no extension it returns an empty string.
path.extname('report.pdf'); // '.pdf'
path.extname('archive.tar.gz'); // '.gz'
path.extname('README'); // ''Here the extension of report.pdf comes back as '.pdf'. With multiple dots, the part after the last dot is taken; that is why 'archive.tar.gz' has the extension '.gz'. It is ideal for branching on file type.
extname examples
extname takes only the part after the last dot. So for double extensions like '.tar.gz' it returns only '.gz'. To get the full package extension you need extra logic.
path.extname('backup.tar.gz'); // '.gz'
path.extname('.gitignore'); // ''In the first example the last dot is before .gz, so the extension is '.gz'. In the second, .gitignore is a hidden file name; the leading dot does not count as an extension and the result is an empty string. This means you must be careful with hidden files.
Practice Your turn: extension with extname
Start with import path from 'path'. Write const ext = path.extname('file.txt'). Log it with console.log(ext).
Starter code
// Import the path module
// Get the extension with path.extname, log with console.logSample solution
import path from 'path';
const ext = path.extname('file.txt');
console.log(ext);Expected output
.txt
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What does path.extname('file.txt') return?
- 'txt'
- 'file'
- '.txt' Correct answer
- 'file.txt'
Explanation: extname returns the extension with the dot.
2 Fill in the blank: extname
import path from 'path';
const ext = path.____('file.txt');
console.log(ext);
import path from 'path';
const ext = path.extname('file.txt');
console.log(ext);
Explanation: You got the extension with extname.
3 extname behaviours
| Term | Meaning |
|---|---|
extname |
returns extension |
dot |
included |
none |
empty string |