Nearby lessons
14 of 21🛣️ Node.js – Path Module
📌 What is Path Module?
What is the Path Module?
The path module in Node.js is a core module that provides utilities for managing file and directory paths. It ensures platform independence and helps handle and transform paths across different operating systems.
The module includes methods for joining, resolving, normalizing paths, and other common file system tasks.
⚙️ Methods in Path Module
- extname
- join
- normalize
- basename
- dirname
- parse
- resolve
- isAbsolute
📌 Method Explanations
path.basename(): Gets the filename portion of a path.path.extname(): Returns the extension of the file.path.dirname(): Returns the directory name of the given path.path.join(): Joins a number of path segments into one path.path.resolve(): Resolves a sequence of paths into an absolute path.path.normalize(): Normalizes a path, resolving.and..segments.path.parse(): Returns an object representing the path with properties:root, dir, base, ext, name.path.isAbsolute(): Checks whether a path is absolute or relative.
📌 Absolute vs Relative Paths
- Absolute Path: Contains the full details to locate a file. Example:
D:\Tutorials\NodeJS\index.js - Relative Path: Does not contain full details. Example:
NodeJS\index.js
🧩 Special Variables
__filename: Returns the filename of the currently executing code with absolute path.__dirname: Returns the absolute path of the directory containing the currently executing file.
💻 Example Usage
Node.js Environment
RUNTIME ACTIVE
const path = require('path'); var filename = 'D:\\Tutorials\\NodeJS\\index.js'; console.log(path.basename(filename)); console.log(path.basename(__filename)); console.log(path.extname(filename)); console.log(path.dirname(filename)); console.log(path.join('users','category','diagrams','flowchart')); console.log(path.join(__dirname,'users','category','diagrams','flowchart')); console.log(path.resolve('users','category','diagrams','flowchart')); var filename1 = 'D:\\Tutorials\\NodeJS\\index.js'; console.log(path.normalize(filename1)); var filename2 = 'D:\\Tutorials\\..\\NodeJS\\index.js'; console.log(path.normalize(filename2)); var filename3 = 'D:\\Tutorials\\NodeJS\\..\\index.js'; console.log(path.normalize(filename3)); console.log(path.join('users','category','diagrams','flowchart','..')); console.log(path.join('users','category','diagrams','flowchart','..','..')); console.log(path.parse(filename)); console.log(path.parse(filename).base); console.log(path.parse(filename).ext); console.log(path.parse(filename).root); console.log(path.parse(filename).name); console.log(path.isAbsolute(filename)); console.log(path.isAbsolute('NodeJS\\index.js'));
Terminal Output
🧠 Test Your Knowledge
4 QuestionsProgress: 0 / 4
Keep Going!Module Scope & Wrapper Function in Node.js