Node.js | path.join() Method

The path.join() method is used to join a number of path-segments using the platform-specific delimiter to form a single path. The final path is normalized after the joining takes place. The path-segments are specified using comma-separated values.

Syntax: 

path.join( [...paths] )

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

  • paths: It is a comma-separated sequence of paths that would be joined together to make the final path.

Return Value: It returns a string with the complete normalized path containing all the segments.

Below examples illustrate the path.join() method in Node.js:



Example 1: 

Node.js

filter_none

edit
close

play_arrow

link
brightness_4
code

// Node.js program to demonstrate the   
// path.join() Method  
  
// Import the path module
const path = require('path');
   
// Joining 2 path-segments
path1 = path.join("users/admin/files", "index.html");
console.log(path1)
   
// Joining 3 path-segments
path2 = path.join("users", "geeks/website", "index.html");
console.log(path2)
   
// Joining with zero-length paths
path3 = path.join("users", "", "", "index.html");
console.log(path3)

chevron_right


Output: 

users\admin\files\index.html
users\geeks\website\index.html
users\index.html

Example 2: 

Node.js

filter_none

edit
close

play_arrow

link
brightness_4
code

// Node.js program to demonstrate the   
// path.join() Method  
  
// Import the path module
const path = require('path');
   
// Normalizing of the final path
path1 = path.join("users", "..", "files", "readme.md");
console.log(path1)
   
// Zero length final path
// returns a period (.)
path2 = path.join("users", "..");
console.log(path2)
   
// Getting the directory path one folder above
console.log("Current Directory: ", __dirname);
path3 = path.join(__dirname, "..");
console.log("Directory above:", path3)

chevron_right


Output: 

files\readme.md
.
Dirname:  G:\tutorials\nodejs-path-join
Directory above: G:\tutorials

Reference: https://nodejs.org/api/path.html#path_path_join_paths




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.