Node.js path.join() Method

Last Updated : 3 Jun, 2026

path.join() is a Node.js method from the path module that combines multiple path segments into a properly formatted file path, ensuring compatibility across different operating systems.

  • Automatically uses the operating system's path separator
  • Cleans up unnecessary separators in the resulting path
  • Simplifies dynamic path creation for files and directories
  • Improves portability of code between Windows, Linux, and macOS systems

Syntax

path.join(path1, path2, ..., pathN)

where,

  • path1, path2, ..., pathN: These are the path segments that are joined together. You can provide multiple path segments, and the function will join them correctly.

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

Example 1: 

JavaScript
import path from 'path';

// Joining 2 path-segments
let path1 = path.join("users/admin/files", "index.html");
console.log(path1)

// Joining 3 path-segments
let path2 = path.join("users", "geeks/website", "index.html");
console.log(path2)

// Joining with zero-length paths
let path3 = path.join("users", "", "", "index.html");
console.log(path3)

This demonstrate the path.join() method. It combines path segments, handling various cases like joining two or three segments and handling zero-length paths effectively.

Output:

path-method
path.join() method in Node.js

Example 2:

JavaScript
// 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)

Here we use the path.join() method. It normalizes the final path, handles zero-length paths, and retrieves the directory path one folder above the current directory using __dirname.

Output: 

using-__dirname
Node.js path.join() Method

Use Cases of path.join()

  • Creating file paths for reading or writing files
  • Building directory paths dynamically at runtime
  • Generating cross-platform paths compatible with different operating systems
  • Combining a project's root directory with subfolders and filenames
  • Constructing paths for serving static assets such as images, CSS, and JavaScript files
Comment

Explore