← Back to Node.js Course | Chapter 2: Core Modules | Lesson 2 of 7

path module

The path module builds and takes apart file paths correctly on every operating system.

In this page:

  1. path module
Syntax
javascript
const path = require('path');
path.join(segment1, segment2)
path.resolve(segment)
path.basename(filePath)
path.extname(filePath)

path module

path.join joins segments with the right separator, path.resolve builds an absolute path, and path.basename, dirname and extname split paths apart. Using path avoids bugs from hand-built strings with slashes.

Note: Use path.join(__dirname, "file") to reference files next to your script.

Example: path module

javascript
const path = require("path");
console.log(path.join("a", "b", "..", "c.txt"));
console.log(path.basename("/tmp/app/index.js"));
console.log(path.extname("photo.final.png"));
console.log(path.dirname("/tmp/app/index.js"));
console.log(path.parse("/home/u/file.txt").name);

// Output:
// a/c.txt
// index.js
// .png
// /tmp/app
// file

⚠️ Run this in your own terminal or Node.js environment.

Related Topics
Common Mistakes
  1. Concatenating paths with plus signs
  2. Hard-coding backslashes
  3. Confusing join with resolve
Chapter Summary
  • join combines segments
  • resolve makes absolute paths
  • basename, dirname, extname split paths
  • Works across operating systems
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.