Labs ICT
Pro Login

Path Module

Work with file paths across operating systems.

Path Module

The path module handles file paths across different operating systems. Windows uses backslashes, Unix uses forward slashes. The path module abstracts this away.

Joining Paths

const path = require("path");

// Join paths (cross-platform)
const fullPath = path.join(__dirname, "data", "users.json");
// /home/user/project/data/users.json

// Resolve to absolute path
const absolute = path.resolve("data", "users.json");

Always Use path.join(): Never concatenate paths with string concatenation like dir + "/" + file. Use path.join() instead — it handles slashes correctly on all platforms.

Try it Yourself →

Parsing Paths

const filePath = "/home/user/project/app.js";

path.dirname(filePath);   // "/home/user/project"
path.basename(filePath);  // "app.js"
path.extname(filePath);   // ".js"

// Parse full path
path.parse(filePath);
// {
//   root: '/',
//   dir: '/home/user/project',
//   base: 'app.js',
//   ext: '.js',
//   name: 'app'
// }

Other Useful Methods

// Check if path is absolute
path.isAbsolute("/home");  // true
path.isAbsolute("home");   // false

// Get relative path
path.relative("/home/user", "/home/user/project/app.js");
// "project/app.js"

// Normalize path
path.normalize("/home/user//project/../project/app.js");
// "/home/user/project/app.js"