Working with Path Module
1. Joining Paths (path.join)
Example
import path from "node:path";
path.join("/foo", "bar", "baz/asdf", "..", "qux"); // "/foo/bar/baz/qux"
2. Resolving Absolute Paths (path.resolve)
| Behavior | Detail |
|---|---|
| Right-to-left | Stops at first absolute path |
Uses process.cwd() | If no absolute path supplied |
3. Getting Directory Name (path.dirname)
| Input | Output |
|---|---|
/a/b/c.js | /a/b |
foo | . |
4. Getting Base Name (path.basename)
| Call | Returns |
|---|---|
basename("/a/b/c.js") | c.js |
basename("/a/b/c.js", ".js") | c |
5. Getting File Extension (path.extname)
| Input | Output |
|---|---|
index.js | .js |
archive.tar.gz | .gz |
.hidden | "" |
6. Normalizing Paths (path.normalize)
| Input | Output |
|---|---|
/foo/bar//baz/qux/.. | /foo/bar/baz |
7. Checking Absolute Paths (path.isAbsolute)
| Path | Result |
|---|---|
/foo | true (POSIX) |
C:\foo | true (Windows) |
./foo | false |
8. Getting Relative Paths (path.relative)
9. Parsing Paths (path.parse)
| Field | Example |
|---|---|
root | / |
dir | /home/user |
base | file.txt |
name | file |
ext | .txt |
10. Formatting Paths (path.format)
| Input Object | Output |
|---|---|
{ dir: "/foo", base: "bar.js" } | /foo/bar.js |
{ name: "x", ext: ".y" } | x.y |
11. Using Platform-Specific Separators
| Property | POSIX | Windows |
|---|---|---|
path.sep | / | \ |
path.delimiter | : | ; |
path.posix.* | Force POSIX | — |
path.win32.* | — | Force Windows |