DevAcademy
LearnNode.jsThe path Module
BeginnerNode.js

The path Module

Build and manipulate file paths correctly across operating systems.

Reading Time

8 min

Lesson

Lesson 8 of 34

Why Not Just Use Strings?

Windows uses backslashes (C:\Users\...) while macOS/Linux use forward slashes (/home/user/...). Manually concatenating path strings with + breaks the moment your code runs on a different OS — the path module abstracts this away.

Joining Paths Safely

Try it yourself — edit and run

Console Output

Click “Run” to see the console output here.

Common path Methods

MethodPurpose
path.join(...)Combine path segments using the correct OS separator
path.resolve(...)Resolve segments into an absolute path
path.basename(p)The final segment (filename) of a path
path.extname(p)The file extension
path.dirname(p)The containing directory

Extracting Path Information

Try it yourself — edit and run

Console Output

Click “Run” to see the console output here.

__dirname Equivalent in ES Modules

Try it yourself — edit and run

Console Output

Click “Run” to see the console output here.

Best Practice

Never manually concatenate path segments with + or template literals — always use path.join() or path.resolve(), which handle separators and normalization correctly on every operating system.

Interview Questions

Quick Quiz

1. Why does the path module exist instead of manually building paths with string concatenation?

2. What does path.extname("photo.jpg") return?

3. Are __dirname and __filename automatically available in ES Modules the same way as CommonJS?