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 Send Emails in Node.js using Nodemailer and Ethereal

How to Send Email in Node.js using Nodemailer Email functionality is essential in modern web applications. Whether you're sending confirmation emails, password resets, or notifications, Node.js with Nodemailer makes this simple. In this blog, we'll walk through setting up email sending using Node.js , Express , and Ethereal Email for testing. ๐Ÿงพ Prerequisites Node.js installed Basic knowledge of Express.js Internet connection ๐Ÿ“ Project Structure project-folder/ ├── index.js ├── .env ├── package.json └── app/ └── controller/ └── emailSendController.js ๐Ÿ“ฆ Step 1: Install Dependencies npm init -y npm install express nodemailer dotenv npm install --save-dev nodemon ๐Ÿ” Configure nodemon (Optional but Recommended) Update your package.json with a custom start script: "scripts": { "start": "nodemon index.js" } ๐Ÿ” Step 2: Create a .env File Create a .env file a...