Node.js Reference ยท path, os and url
Node.js path.normalize() method
Reference for path.normalize() in Node.js: tidy a path by collapsing repeated separators and resolving . and .. segments, with edge cases and platform notes.
path.normalize() cleans up a single path string. It collapses repeated separators (// becomes /), removes . segments and resolves .. segments by dropping the folder before them. It does not make the path absolute and it does not check that anything exists.
Most of the time you do not call it directly, because path.join() and path.resolve() already normalize their results. It is useful when a whole path arrives as one string, from a config file or a command-line flag.
import path from "node:path"; path.normalize("/srv//app/./logs/../data"); // "/srv/app/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.normalize(path): string
| Name | Description |
|---|---|
path |
The path string to clean up. |
Returns: the normalized path. An empty string gives ".".
Errors: ERR_INVALID_ARG_TYPE if path is not a string.
Usage notes
- Relative stays relative. Leading
..segments of a relative path are kept (../x), because there is no known parent to drop. On an absolute path they are removed at the root (/..is/). - A trailing separator survives.
docs/anddocsstay different strings, so strip it yourself if you need to compare them. - A path that cancels itself gives
..a/..becomes., never an empty string. - Purely textual.
normalizedoes not look at the file system, so it does not follow symbolic links.link/..is treated as the parent oflinkin the string, which can differ from the real parent on disk. Usefs.realpath()when links matter. - Not a security filter. Normalizing user input is not enough to stay inside a folder. A normalized path can still start with
... See Path traversal. - Platform rules apply. On Windows it also converts
/to\, and understands drive letters and UNC prefixes. Usepath.posix.normalizeorpath.win32.normalizeto force one set of rules. - Case is untouched. Windows and macOS file systems are often case-insensitive, but
normalizenever changes letter case.