Skip to content
Tutorials Center
My learning

Topics

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.

NODE
import path from "node:path";

path.extname("notes/todo.md");   // ".md"

Try it

Node.js What counts as an extension

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.

Node.js Dispatching on the extension

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

NODE
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.gz gives .gz. If you care about double extensions, check the name with endsWith(".tar.gz").
  • Leading dots are not extensions. .gitignore has an empty extension, but .config.json gives .json.
  • A trailing dot gives just ".". photo. returns ".". This is easy to overlook when validating user input.
  • Case is preserved. file.JPG returns .JPG. Compare with toLowerCase() 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 basename to strip it: path.basename(file, path.extname(file)) returns the name without the extension, which works for any extension.
  • Use path.parse() to get name and ext in one call.