Skip to main content

Node.js Path Module – Complete Notes with Real Use Cases

Node.js Path Module – Notes with Use Cases
💡 The path module in Node.js provides utilities to work with file and directory paths. It is built-in and can be imported using:
const path = require('path');

✅ path.basename(path)

Returns: The filename from a full path.

Use Case: Extract file name during file upload logging.

path.basename('C:\\temp\\abcd.html'); 
// Output: 'abcd.html'

✅ path.dirname(path)

Returns: The directory portion of the path.

Use Case: Get parent directory before saving a file.

path.dirname('foo\\abcd\\test.html'); 
// Output: 'foo\\abcd'

✅ path.extname(path)

Returns: The file extension from the path.

Use Case: Validate file type before processing upload.

path.extname('test.html');        // '.html'
path.extname('file.name.md');     // '.md'
path.extname('.hiddenfile.txt');  // '.txt'
path.extname('filename');         // ''
path.extname('.config');          // ''

✅ path.format(pathObject)

Returns: A full path string from a path object.

Use Case: Dynamically construct a path from user input.

path.format({
  dir: 'foo\\dir',
  base: 'abcd.txt'
});
// Output: 'foo\\dir\\abcd.txt'

✅ path.isAbsolute(path)

Returns: true if the path is absolute, else false.

Use Case: Ensure path safety before file operations.

path.isAbsolute('C:\\folder');  // true
path.isAbsolute('.');           // false
path.isAbsolute('');            // false

✅ path.join([...paths])

Returns: A normalized path by joining segments.

Use Case: Construct safe file paths across platforms.

path.join('foo', 'bar', 'file.txt'); 
// Output: 'foo\\bar\\file.txt'

path.join('foo', {}, 'file'); 
// Throws TypeError

✅ path.relative(from, to)

Returns: The relative path from one location to another.

Use Case: Generate relative paths for reports or internal links.

path.relative('C:\\a\\b', 'C:\\a\\c\\d'); 
// Output: '..\\c\\d'

✅ path.resolve([...paths])

Returns: An absolute path from right-to-left evaluated segments.

Use Case: Use in CLI or config files to get full absolute paths.

path.resolve('foo', 'bar'); 
// Output: 'C:\\current\\dir\\foo\\bar'

✅ path.sep

Returns: The platform-specific path separator.

Use Case: Write cross-platform code that involves file system paths.

console.log(path.sep);
// Output: '\' on Windows, '/' on macOS/Linux

🔚 Conclusion

The path module is extremely helpful when dealing with file systems in Node.js. Whether you're building CLI tools, managing file uploads, or automating directory structures, these methods ensure your code is clean, cross-platform, and error-free.

📌 Save this as a quick reference or bookmark it for later!

Comments

Popular posts from this blog

How to Display Flash Messages in EJS using Node.js and Express

Displaying Flash Messages in EJS with Node.js and Express Flash messages are a great way to give users quick feedback — like "Login successful!" or "Please enter all fields!" . In this guide, you’ll learn how to implement them using: express-session connect-flash EJS templating 📦 Step 1: Install Required Packages npm install express express-session connect-flash ejs ⚙️ Step 2: Setup Express App and Middleware const express = require('express'); const session = require('express-session'); const flash = require('connect-flash'); const app = express(); // Set view engine app.set('view engine', 'ejs'); // Middleware app.use(express.urlencoded({ extended: true })); app.use(session({ secret: 'yourSecretKey', resave: false, saveUninitialized: true })); app.use(flash()); // Make flash messages available to all views app.use((req, res, next) => { res.lo...

Realtime Device Tracker using Node.js, Socket.IO & Leaflet

Realtime Device Tracker using Node.js, Socket.IO & Leaflet In this tutorial, you’ll learn how to build a realtime location tracking application that uses the browser’s GPS, Socket.IO for live communication, and Leaflet.js to display users on a map. 🚀 Project Overview Backend: Node.js, Express.js, Socket.IO Frontend: HTML, Leaflet.js, Socket.IO client Features: Live GPS tracking, multi-user map, disconnect cleanup 📁 Folder Structure project-root/ ├── app.js ├── package.json ├── src/ │ ├── public/ │ │ ├── css/ │ │ │ └── style.css │ │ └── js/ │ │ └── script.js │ ├── routes/ │ │ └── routers.js │ ├── socket/ │ │ └── socketHandler.js │ └── views/ │ └── index.ejs 🧠 How It Works Each user shares their location using the browser's navigator.geolocation API. Location is sent to the server via Socket.IO . The server broadcasts each user’s position to all clien...

How to Use L5-Swagger for API Documentation in Laravel

Integrating Swagger in Laravel: Annotations, JSON, and YAML What is Swagger? Swagger (OpenAPI) is a powerful tool for generating interactive API documentation. It helps developers understand and test your API easily. ✅ Step-by-Step Guide to Setup L5-Swagger 1. Install L5-Swagger Package composer require "darkaonline/l5-swagger" 2. Publish Config & View Files This command publishes the config file to config/l5-swagger.php : php artisan vendor:publish --provider "L5Swagger\L5SwaggerServiceProvider" 3. Configure Swagger (Optional) Edit the file config/l5-swagger.php to update: API Title Base Path Directories to scan for annotations 4. Add Swagger Annotations Add these before your controller class: /** * @OA\Info( * version="1.0.0", * title="Your API Title", * description=...