NodeJS by Example: Path Module
|
The Path module provides utilities for working with file and directory paths. It handles the differences between operating systems (Windows uses \, Unix uses /). |
|
|
Import specific functions from the path module |
|
|
Joining Paths join() combines path segments using the platform-specific separator. It normalizes the result. Unix: 'users/documents/file.txt' Windows: 'users\\documents\\file.txt' It handles ./ and ../ correctly |
|
|
Resolving Absolute Paths resolve() creates an absolute path. It processes from right to left until an absolute path is formed. Returns: /current/working/dir/src/utils/helper.js If you provide an absolute path, it uses that as the base |
|
|
Getting Directory Name dirname() returns the directory portion of a path. |
|
|
Getting File Name basename() returns the last portion of a path. Optionally removes the extension. |
|
|
Getting Extension extname() returns the file extension, including the dot. |
|
|
Parsing Paths parse() breaks a path into its components: root, dir, base, ext, name. { root: '/', dir: '/home/user/docs', base: 'report.pdf', ext: '.pdf', name: 'report' } |
|
|
Formatting Paths format() is the opposite of parse() - it builds a path from components. |
|
|
Normalizing Paths normalize() cleans up a path by resolving . and .. segments and removing redundant separators. |
|
|
Checking Absolute Paths isAbsolute() returns true if the path is absolute. |
|
|
Relative Paths relative() calculates the relative path between two absolute paths. |
|
|
Platform Separator sep is the platform-specific path separator. |
|
|
Practical Example Common pattern: get the directory of the current module and build paths from it. Build paths relative to current module |
|