Skip to content
Tutorials Center
My learning

Topics

Node.js Reference ยท path, os and url

Node.js path.basename() method

Reference for path.basename() in Node.js: get the last segment of a path, strip an extension with the suffix argument, and handle trailing slashes and edge cases.

path.basename() returns the last segment of a path: normally the file name. An optional second argument removes a suffix, which is the quick way to get a name without its extension.

It only looks at the string. It does not check whether the path is a file or a folder, or whether it exists.

NODE
import path from "node:path";

path.basename("/srv/app/report.pdf");           // "report.pdf"
path.basename("/srv/app/report.pdf", ".pdf");   // "report"

Try it

Node.js File names and suffixes

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 Removing any extension, and platform rules

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.basename(path[, suffix]): string
Name Description
path The path to examine.
suffix Optional text to remove from the end of the result. Match is exact and case-sensitive on POSIX.

Returns: the last segment, without trailing separators. The result is "" for the root path and for an empty string.

Errors: ERR_INVALID_ARG_TYPE if path or suffix is not a string.

Usage notes

  • Trailing separators are ignored. /srv/app/ has the base name app, not an empty string.
  • The suffix is literal. Pass ".pdf" with the dot, otherwise "pdf" would also strip from "report.pdf" leaving "report.". There is no wildcard and no automatic extension detection.
  • A suffix that equals the whole name is not removed. path.basename("a.txt", "a.txt") stays "a.txt", so you never get an empty name back.
  • Dot files. .gitignore is a base name with no extension. Combining basename with path.extname() handles it correctly because extname returns "" for it.
  • Only the last extension is stripped by a single suffix. For archive.tar.gz, .gz leaves archive.tar.
  • Platform rules matter. On POSIX only / separates segments. Parse Windows paths with path.win32.basename.
  • Do not trust it for security. The result of basename of user input is a common way to drop directories from an upload name, but it still can be .. or .. Reject those explicitly.
  • Use path.parse() when you need the name, extension and folder at once.