API Reference
pathlib-ts mirrors CPython 3.14’s pathlib module but adapts it to TypeScript, an async-first programming style, and the Node-compatible runtime surface. This page summarises the major classes and highlights the places where the port intentionally diverges.
Class overview
Section titled “Class overview”PurePath– lexical path manipulation with no I/O. Subclasses:PurePosixPath,PureWindowsPath.Path– extends the hostPure*flavour and adds filesystem methods. Subclasses:PosixPath,WindowsPath.DefaultPathpicks the correct subclass for the current OS.UnsupportedOperation– thrown when a runtime feature such asfs.readdir(..., { withFileTypes: true })orfs.globSyncis missing.
PurePath essentials
Section titled “PurePath essentials”| Feature | CPython parity | Notes |
|---|---|---|
parts, anchor, drive, root, name, suffix, suffixes, stem | ✅ | Implemented in src/purepath.ts; caches results lazily. |
joinpath(...segments) | ✅ | Always returns the same subclass; use withSegments for custom subclasses. |
relativeTo(other, { walkUp }) | ✅ | Throws when anchors disagree unless walkUp is provided. |
isRelativeTo(other) | ✅ | Wraps relativeTo and catches errors. |
match(), fullMatch() | ✅ | Support for *, ?, ** (full match only), and character classes. |
asPosix() | ✅ | Converts separators to / on Windows. |
asURI() / fromURI() | ✅ | Requires absolute paths. |
TypeScript conveniences
Section titled “TypeScript conveniences”withSegments(...segments)is public and overridable, mirroring CPython 3.14’s new hook for derivative paths.dropSegments(count)is exposed to support policies inPath.relativeTo().
Path-specific functionality
Section titled “Path-specific functionality”Every I/O method comes in two flavours:
- Async default (returns
Promise<T>). - Sync variant with a
Syncsuffix.
This is achieved via the small toPromise() helper in src/util.ts, so both flavours always share the same implementation.
Metadata & stat helpers
Section titled “Metadata & stat helpers”infolazily constructs aPathInfo(orDirEntryInfowhen the path originated from aDirent) and caches it per instance.stat,lstat,exists,isDir,isFile,isSymlinkmirror CPython semantics and acceptfollowSymlinkswhere appropriate.
Directory listing
Section titled “Directory listing”iterdir, iterdirSync and iterdirStream support the Node-style dirent toggle:
const dir = new Path("./dist");
const entries = await dir.iterdir(); // Path[] (default)const dirents = await dir.iterdir({ extra: { withFileTypes: true } }); // Dirent[]- When
withFileTypesistrue, the runtime must providefs.readdir(..., { withFileTypes: true }); otherwiseUnsupportedOperationis thrown. - Streaming variants (
iterdirStream,iterdirStreamSync) usefs.opendir*when available to reduce memory footprint.
Children created from iterdir*() calls inherit cached metadata via DirEntryInfo, ensuring that subsequent isFile()/isDir() checks can avoid extra syscalls when the runtime exposes that data.
Globbing and tree walking
Section titled “Globbing and tree walking”glob(pattern)andrglob(pattern)require Node 20+ (or Bun/Deno equivalents) wherefs.glob/fs.globSyncexist. The library raisesUnsupportedOperationif the feature is missing.walk({ topDown })mirrorsos.walk(), yielding tuples of[Path, dirNames[], fileNames[]].
File I/O
Section titled “File I/O”readText,readBytes,writeText,writeBytes, andopenmap directly tofs.readFile,fs.writeFile, andfs.createReadStream. For write operations, sync variants callfs.writeFileSync.touch({ mode, existOk }),mkdir({ parents, existOk, mode }),unlink({ missingOk }),rmdir(),rename,replace,copy, andreadlinkare built atop the matchingfsmethods.copyleveragesfs.cpSync(recursive) and performs best-effort validation viaensureDistinctPaths.
Relative path policies
Section titled “Relative path policies”Path.relativeTo() and Path.isRelativeTo() introduce policy-aware semantics that do not exist in upstream CPython:
const asset = new Path("/repo/assets/img.png");const mdx = new Path("/repo/content/post.mdx");
// Purely lexical (default policy)asset.relativeTo(mdx, { walkUp: true }).toString(); // '../assets/img.png'
// Interpret the right operand as a file and anchor at its parentasset.relativeTo(mdx, { walkUp: true, extra: { policy: "parent" } }).toString();
// Auto-detect using filesystem metadata (async)const rel = await asset.relativeTo(mdx, { walkUp: true, extra: { policy: "auto", followSymlinks: true },});Policy summary:
| Policy | Behaviour | Return type |
|---|---|---|
"exact" (default) | CPython lexical semantics. | PurePath |
"parent" | Treat other.parent as the anchor, no I/O. | PurePath |
"auto" | Stat other to detect directories; respects followSymlinks. | Promise<PurePath> |
Path.isRelativeTo() accepts the same policy options. When policy === "auto", it returns a Promise<boolean>; otherwise it stays synchronous.
Environment helpers
Section titled “Environment helpers”Path.cwd()/Path.cwdSync()andPath.home()/Path.homeSync()mirror CPython’s class methods.absolute()returns an absolute path without resolving symlinks;resolve()resolves symlinks and normalises, just like Python.expandUser()expands~prefixes usingnode:os.homedir().
Unsupported and intentionally omitted features
Section titled “Unsupported and intentionally omitted features”src/os.ts documents the omitted low-level syscall helpers (e.g. reflink/copy_file_range). The omissions are deliberate to keep the runtime portable. If you attempt to exercise a method that needs a missing runtime primitive, expect UnsupportedOperation.
TypeScript typing tips
Section titled “TypeScript typing tips”- Most APIs return
Pathbut TypeScript recognises the inheritance chain, so you can rely onPurePathmembers onPathinstances without extra casts. - The promise vs sync overloads preserve narrow return types (
Promise<Path>vsPath) thanks to overload definitions. - The policy-aware overloads for
relativeTo/isRelativeToare strongly typed; misuse will surface as a compile-time error before it reaches runtime tests.
For deep dives into behavioural edge cases, study the tests in tests/—they mirror CPython’s behaviour wherever feasible and document the deliberate deviations.