Node.js Course
Node.js
/
Beginner

Path Module

Definition

A core module that provides utilities for working with file and directory paths safely across different operating systems.

Explain Like I'm New

Macs use forward slashes (`/Users/admin/file`). Windows uses backslashes (`C:\Users\admin\file`). If you hardcode slashes in your code, your app will break when someone runs it on a different computer. The `path` module automatically calculates the correct slashes for whatever OS the code is currently running on.

Real World Example

Connecting a static public folder in Express: `app.use(express.static(path.join(__dirname, 'public')))` guarantees the folder is found regardless of Windows or Mac.

Common Use Cases

  • •Cross-platform file manipulation
  • •Extracting file extensions (.jpg, .txt) from strings

Terminal Output

bash / terminal
const path = require('path'); // 1. Safely glueing paths together // If running on Windows, this outputs: folder\subfolder\file.txt // If running on Mac/Linux, outputs: folder/subfolder/file.txt const safePath = path.join('folder', 'subfolder', 'file.txt'); console.log("Joined Path:", safePath); // 2. Getting file info const filePath = '/var/www/website/index.html'; console.log("Base name:", path.basename(filePath)); // 'index.html' console.log("Extension:", path.extname(filePath)); // '.html' console.log("Directory:", path.dirname(filePath)); // '/var/www/website' // 3. Creating an Absolute Path (Resolves relative to your current working directory) const absolute = path.resolve('public', 'css', 'style.css'); console.log("Absolute Path:", absolute);

Interview Questions

basic

  • What does `path.join()` do?

intermediate

  • What is the difference between `path.join()` and `path.resolve()`?

advanced

  • How do you get just the filename ('image.png') from a massive file path string?

Flash Cards

Question

join vs resolve?

Click to reveal answer
Answer

`path.join('a', 'b')` simply glues them together: `a/b`. `path.resolve('a', 'b')` resolves to an ABSOLUTE path from the root of your hard drive, acting like the `cd` command in a terminal.

Question

How to get the filename?

Click to reveal answer
Answer

Use `path.basename('/users/admin/desktop/image.png')`. It will return exactly `'image.png'`.