Node.js Reference ยท path, os and url
Node.js path.resolve() method
Reference for path.resolve() in Node.js: turn segments into an absolute path, how it reads right to left, falls back to the working directory and differs from join.
path.resolve() turns a sequence of path segments into one absolute path. It processes the segments from right to left and stops as soon as it has built an absolute path. If the segments never form one, it prepends the process's current working directory, process.cwd().
It is like typing cd commands one after another and asking where you ended up. The result is always normalized and never has a trailing separator (except for the root).
import path from "node:path"; path.resolve("/srv", "app", "..", "data"); // "/srv/data"
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.resolve([...paths]): string
| Name | Description |
|---|---|
...paths |
Zero or more segments, processed from right to left. Empty strings are ignored. |
Returns: an absolute, normalized path. With no arguments it returns the current working directory.
Errors: ERR_INVALID_ARG_TYPE if a segment is not a string.
Usage notes
- An absolute segment wins. Everything to its left is discarded.
path.resolve("/a", "/b")is/b. This is the main difference frompath.join(), which keeps both. resolvedepends onprocess.cwd()when no segment is absolute. The same code can give different answers when started from another folder. For files that ship with your code, resolve againstimport.meta.dirname(or__dirnamein CommonJS) instead.- Trailing separators are removed.
path.resolve("/srv/app/")is/srv/app. The root/keeps its slash. - It never checks the disk. The path does not need to exist and symbolic links are not followed. Use
fs.realpath()to resolve links. - Use it to compare paths. Resolving both sides first removes differences such as
./a/../bversusb. - Safe-folder check:
path.resolve(base, input)followed by astartsWith(base + path.sep)test is the usual guard against traversal. See Path traversal. - On Windows an input such as
C:or\\server\sharehas its own drive rules, andpath.resolve("D:foo")uses the working directory of that drive. Prefer fully qualified paths there. - Performance: it is pure string work, but when it needs
process.cwd()it makes a system call. Cache the result in a hot loop.