0
0
Node.jsframework~5 mins

path.extname for file extensions in Node.js

Choose your learning style9 modes available
Introduction
The path.extname function helps you find the file extension from a file name or path. It makes it easy to know what type of file you are working with.
When you want to check if a file is a .jpg or .png before processing images.
When you need to filter files by their extensions in a folder.
When you want to add special handling for certain file types in your app.
When you want to rename or change file extensions safely.
When you want to validate file uploads by checking their extensions.
Syntax
Node.js
path.extname(pathString)
The function returns the extension including the dot, like '.txt'.
If the file has no extension, it returns an empty string.
Examples
Gets the extension from a simple file name.
Node.js
path.extname('photo.jpg') // returns '.jpg'
Returns only the last extension part after the last dot.
Node.js
path.extname('/folder/file.tar.gz') // returns '.gz'
Returns empty string if no extension is found.
Node.js
path.extname('README') // returns ''
Files starting with a dot but no extension return empty string.
Node.js
path.extname('.gitignore') // returns ''
Sample Program
This program loops through a list of file names and prints each file's extension using path.extname.
Node.js
import path from 'path';

const files = ['index.html', 'photo.jpg', 'archive.tar.gz', 'README', '.env'];

files.forEach(file => {
  const ext = path.extname(file);
  console.log(`File: ${file} - Extension: '${ext}'`);
});
OutputSuccess
Important Notes
path.extname only returns the last extension after the final dot.
It does not check if the file actually exists or if the extension is valid.
Use this function to quickly identify file types by their extensions.
Summary
path.extname extracts the file extension including the dot.
It returns an empty string if no extension is found.
Useful for filtering or handling files based on their type.