path Module (Node.js)

path is Node.js's built-in module for working with file and directory paths in a cross-platform way. It joins, resolves, and parses paths using the correct separator for the operating system.

Node.js

Hard-coding paths with string concatenation and slashes breaks across operating systems (Windows uses backslashes). The path module handles this for you: path.join('a', 'b', 'c.txt') builds a path with the right separator, and the result works on Linux, macOS, and Windows.

Key functions: path.join() concatenates segments; path.resolve() produces an absolute path (resolving from the current working directory); path.basename(), path.dirname(), and path.extname() pull apart a path; path.parse() returns an object of its parts; and path.sep is the platform separator.

Combine path with __dirname to reference files relative to the current module rather than the process's working directory, which is the robust way to load adjacent files: path.join(__dirname, 'config.json').

Syntax

const path = require("path");
path.join(dir, "file.txt");

Examples

JavaScript

const path = require("path");

const full = path.join(__dirname, "data", "users.json");
console.log(path.basename(full)); // users.json
console.log(path.extname(full));  // .json

Output:

users.json
.json

Learn it in a lesson

See also

Back to the Dictionary