Skip to content
Tutorials Center
My learning

Topics

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.

NODE
import path from "node:path";

path.normalize("/srv//app/./logs/../data");   // "/srv/app/data"

Try it

Node.js What gets cleaned up

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 Normalizing to compare paths

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.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/ and docs stay 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. normalize does not look at the file system, so it does not follow symbolic links. link/.. is treated as the parent of link in the string, which can differ from the real parent on disk. Use fs.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. Use path.posix.normalize or path.win32.normalize to force one set of rules.
  • Case is untouched. Windows and macOS file systems are often case-insensitive, but normalize never changes letter case.