Open In App

Node path.resolve() Method

The path.resolve() method is used to resolve a sequence of path segments to an absolute path. It works by processing the sequence of paths from right to left, prepending each of the paths until the absolute path is created. The resulting path is normalized and trailing slashes are removed as required.
If no path segments are given as parameters, then the absolute path of the current working directory is used.

Syntax: 



path.resolve( [...paths] )

Parameters: This function accepts one parameter as mentioned above and described below: 

Return Value: It returns a string with absolute path. 



Steps to create the application:

Step 1: You can install this package by using this command.

npm install express

Step 2: After installing the express module, you can check your express version in the command prompt using the command.

npm version express

Project Structure:

The updated dependencies in package.json file will look like:

"dependencies": {
"express": "^4.18.2",
}

Example 1: Below programs illustrate the path.resolve() method in Node.js:




// Node.js program to demonstrate the  
// path.resolve() Method 
 
// Import the path module
const path = require('path');
  
console.log("Current directory:", __dirname);
  
// Resolving 2 path-segments
// with the current directory
path1 = path.resolve("users/admin", "readme.md");
console.log(path1)
  
// Resolving 3 path-segments
// with the current directory
path2 = path.resolve("users", "admin", "readme.md");
console.log(path2)
  
// Treating of the first segment
// as root, ignoring the current directory
path3 = path.resolve("/users/admin", "readme.md");
console.log(path3)

Steps to run the program:

node index.js

Output: 

Current directory: G:\tutorials\nodejs-path-resolve
G:\tutorials\nodejs-path-resolve\users\admin\readme.md
G:\tutorials\nodejs-path-resolve\users\admin\readme.md
G:\users\admin\readme.md

Example 2: Below programs illustrate the path.resolve() method in Node.js:




// Node.js program to demonstrate the  
// path.resolve() Method 
 
// Import the path module
const path = require('path');
 
console.log("Current directory:", __dirname);
 
// Normalization of the absolute paths
path1 = path.resolve("users", "..", "readme.md");
console.log(path1)
 
path2 = path.resolve("users", "admin",
    "..", "files", "readme.md");
console.log(path2)
 
path3 = path.resolve("users", "admin",
    "..", "files", "..", "readme.md");
console.log(path3)

Steps to run the program:

node index.js

Output: 

Current directory: G:\tutorials\nodejs-path-resolve
G:\tutorials\nodejs-path-resolve\readme.md
G:\tutorials\nodejs-path-resolve\users\files\readme.md
G:\tutorials\nodejs-path-resolve\users\readme.md

We have a complete list of Node Path Module methods, to check those please go through this Node.js Path Module Complete Reference article


Article Tags :