How to Use path.extname in Node.js to Get File Extensions
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.
const path = require('path'); const ext = path.extname('/folder/file.txt'); console.log(ext); // Outputs: .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.
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)}`); });
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.
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
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
path.extname(path) to get the file extension including the dot.path from Node.js core modules before using.path.extname.