Thuta Learning
IntermediateWeb Developmentbeginner

Path Module

Relax. We'll talk through this in plain words — no textbook voice.

path is a built-in utility that builds file paths correctly regardless of the operating system. Since Windows uses \ and macOS/Linux use /, it's safer to use path.join() than to concatenate strings by hand.

javascript
const path = require('path');

const filePath = path.join(__dirname, 'uploads', 'profile.png');

console.log('Full Path:', filePath);
console.log('File Name:', path.basename(filePath));
console.log('Folder:', path.dirname(filePath));
console.log('Extension:', path.extname(filePath));

__dirname returns the path of the folder the current file is in. path.join() joins path segments together in a way that matches the OS. basename, dirname, and extname pull out different pieces of file info.

You should see
Full Path: /your-project/uploads/profile.png File Name: profile.png Folder: /your-project/uploads Extension: .png

Info

For upload file paths, image paths, template paths, and static file paths, using path.join() cuts down on cross-platform issues.

Easy traps

  • Concatenating strings like __dirname + '/uploads/profile.png' by hand can cause path issues across different operating systems.

Exercise

The path module always comes in handy when setting up things like Express static folders, uploaded file storage, or generated PDF/image output paths.

You'll know it worked when: