Normalize path with Node
06-01-2021 | #nodejs
Normalize path means that the
'.' segments are resolved and path segment separation characters like
\ are replaced with the platform-specific path segment separator.
To normalize the path with Node, you call the
normalize() method of the
const path = require("path")
It receives a path as a parameter
path.normalize("path1/path2\\../path3") // path1\\path3
The path above is resolved at
'..' segment. It goes up from
path1 and continues with
path3. I am using Windows so that the path segment separator is replaced with
If there are multiple separators, they will be replaced with a single separator.
path.normalize("path1/path2////path3") // path1\\path2\\path3
In case you combine
\ in the path, they are still replaced with a platform-specific separator.
path.normalize("path1\\path2//\\path3") // path1\\path2\\path3
The method preserves the trailing separators.
path.normalize("path1/path2/") // path1\\path2\\
If you pass a zero-length string, the method returns
'.', which is the current directory.
path.normalize("") // '.'