Node.js 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:
- paths: It is a series of file paths that would be resolved together to form an absolute path. It throws a TypeError if this parameter is not a string value.
Return Value: It returns a string with absolute path.
Below programs illustrate the path.resolve() method in Node.js:
Example 1:
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) |
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:
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) |
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
Reference: https://nodejs.org/api/path.html#path_path_resolve_paths
Please Login to comment...