The path.relative() method in Node.js helps determine the path required to navigate from one file or directory location to another. It is commonly used when working with file systems where relative paths are preferred over absolute paths.
- It is useful for building links between files and folders in a project.
- It is helpful in tools that need to move up or down folders programmatically.
Syntax:
path.relative(from, to)where,
- from: It is the base path.
- to: It is used to find the relative path.
Return Value: It returns a string with the normalized form of the path.
Example:
// Node.js program to demonstrate the
// path.relative() method
// Import the path module
const path = require('path');
path1 = path.relative("geeks/website", "geeks/index.html");
console.log(path1)
path2 = path.relative("users/admin", "admin/files/website");
console.log(path2)
// When both the paths are same
// It returns blank string
path3 = path.relative("users/admin", "users/admin");
console.log(path3)
In this code,
path.relative()calculates the relative path betweengeeks/websiteandgeeks/index.html.- It then finds the relative path from
users/admintoadmin/files/website. - Finally, it compares two identical paths and produces an empty string because no navigation is required.
Output:
..\index.html
..\..\admin\files\website
Use Cases of path.relative()
- Generate relative paths: Finds the path needed to move from one location to another.
- File linking: Creates references between related files and directories.
- Project portability: Uses relative paths instead of absolute paths, making projects easier to move across systems.
Reference: https://nodejs.org/api/path.html#path_path_relative_from_to