Node.js
path Module
Join, resolve, and parse file paths cross-platform.
By EZ4Code Team
pathfilesystemcross-platform
Code
import path from "path";
import { fileURLToPath } from "url";
// Cross-platform path joining
const file = path.join("/var", "data", "users.json");
const abs = path.resolve("data", "users.json");
const norm = path.normalize("/var/../tmp//x/");
// Parse and format
const parsed = path.parse("/var/www/index.html");
// { root, dir, base, name, ext }
const rebuilt = path.format({ dir: "/tmp", name: "out", ext: ".txt" });
// Relative and basename
path.relative("/a/b/c", "/a/b/d"); // ../d
path.basename("/a/b/index.html"); // index.html
path.basename("/a/b/index.html", ".html"); // index
path.extname("archive.tar.gz"); // .gz
// ESM: derive __dirname (not defined in ES modules)
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);Explanation
The path module handles file paths in a platform-aware way, using backslashes on Windows and forward slashes on POSIX. path.join concatenates segments safely, while path.resolve produces an absolute path from the current working directory. In ES modules, __dirname is unavailable and must be derived from import.meta.url.
More Node.js Snippets
fs Module
Read, write, and watch files with promises and callbacks.
HTTP Server
Build an HTTP server with the http module and routing.
Streams
Pipe, transform, and consume streams efficiently.
EventEmitter
Emit and listen for custom events.
Buffers
Work with binary data using Buffer and TypedArrays.
Child Process
Spawn, exec, and fork external processes.