Node.js Reference ยท path, os and url
Node.js path.dirname() method
Reference for path.dirname() in Node.js: get the directory part of a path, how trailing slashes and the root behave, and how to walk up folder by folder.
path.dirname() returns everything in a path except the last segment: the folder that contains the file. It is the counterpart of path.basename(), and together they split a path in two.
It works on the string alone. Calling it on a path that does not exist is fine.
import path from "node:path"; path.dirname("/srv/app/report.pdf"); // "/srv/app"
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.dirname(path): string
| Name | Description |
|---|---|
path |
The path whose directory part you want. |
Returns: the path without its last segment. For a path with no directory part it returns ".", and for the root it returns the root.
Errors: ERR_INVALID_ARG_TYPE if path is not a string.
Usage notes
- Trailing separators are ignored.
dirname("/srv/app/")is/srv, becauseappis treated as the last segment even if it is a folder. - No directory gives
..dirname("report.pdf")is the current directory, written".", which makes the result safe to pass topath.join(). - The root is its own parent.
dirname("/")is/. This is what makes a "walk up" loop terminate when the value stops changing. - It does not clean the string. Unlike
path.normalize(), it keeps.and..segments that appear before the last part. Normalize first if the input is untidy. - Finding your own folder: in an ES module,
import.meta.dirnameis the directory of the current file, which equalspath.dirname(import.meta.filename). In CommonJS use__dirname. See import.meta. - Creating the parent folder before writing:
await fs.mkdir(path.dirname(target), { recursive: true }). - Platform rules: on Windows the drive root (
C:\) is the end of the walk and/is also accepted as a separator. Usepath.win32.dirnameorpath.posix.dirnameto choose.