The path.normalize() method in Node.js converts a path into a standardized format by resolving . and .. segments and removing redundant path separators. It helps ensure that file paths are interpreted consistently across different environments.
- Resolves
.and..segments to their correct locations. - Replaces repeated path separators with a single separator.
- Preserves trailing path separators.
Syntax:
path.normalize(path)Parameters:
- path: The path string to normalize.
Return Value: A normalized path string.
Example:
// Node.js program to demonstrate the
// path.normalize() method
// Import the path module
const path = require('path');
path1 = path.normalize("/users/admin/.");
console.log(path1)
path2 = path.normalize("/users/admin/..");
console.log(path2)
path3 = path.normalize("/users/admin/../comments")
console.log(path3);
path4 = path.normalize("/users///admin///comments")
console.log(path4);
In this code,
path.normalize()is used on different paths to clean and standardize them.- Paths containing
.and..are resolved to their normalized locations. - Multiple consecutive slashes are reduced to a single slash in the final path.
Output:
\users\admin
\users
\users\comments
\users\admin\comments
Use Cases of Node.js path.normalize()
- Cleaning user-provided paths: Standardizes paths entered by users before processing them.
- Resolving relative path segments: Converts paths containing
.and..into a cleaner and more accurate form. - Removing duplicate separators: Fixes paths with multiple consecutive slashes or backslashes.
- Handling dynamically generated paths: Normalizes paths created by combining strings from different sources.
Reference: https://nodejs.org/api/path.html#path_path_normalize_path