Node.js Reference ยท path, os and url
Node.js path.extname() method
Reference for path.extname() in Node.js: get a file extension including the dot, with the rules for dot files, double extensions and trailing dots.
path.extname() returns the extension of the last segment of a path, starting at the last . and including that dot. If the name has no extension, it returns an empty string.
It is what you reach for when you branch on the type of a file: .json, .md, .png. It is purely textual and never opens the file.
import path from "node:path"; path.extname("notes/todo.md"); // ".md"
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.
Syntax
path.extname(path): string
| Name | Description |
|---|---|
path |
The path to examine. |
Returns: the extension of the last segment, including the leading dot, or "" if there is none.
Errors: ERR_INVALID_ARG_TYPE if path is not a string.
Usage notes
- Only the last dot counts.
archive.tar.gzgives.gz. If you care about double extensions, check the name withendsWith(".tar.gz"). - Leading dots are not extensions.
.gitignorehas an empty extension, but.config.jsongives.json. - A trailing dot gives just
".".photo.returns".". This is easy to overlook when validating user input. - Case is preserved.
file.JPGreturns.JPG. Compare withtoLowerCase()when you match known types. - Only the last segment is examined. The dot in a folder name (
a.b/c) is ignored, and a trailing separator is skipped. - The extension is only a naming convention. It does not prove the content type. Never trust it to decide whether an uploaded file is safe.
- Pair with
basenameto strip it:path.basename(file, path.extname(file))returns the name without the extension, which works for any extension. - Use
path.parse()to getnameandextin one call.