Path Module

Last Updated : Oct 2026


Different operating systems handle file paths differently:

  • Windows uses backslashes (C:\users\project\index.js).
  • macOS/Linux use forward slashes (/users/project/index.js).

If you hardcode slashes in your strings, your app might break when deployed to a cloud server (which usually runs Linux). The path module solves this by normalizing paths automatically.

Import the path module using CommonJS:

const path = require("node:path");

Import the path module using ESM :

import path from "node:path";

Some commonly used methods in the path module are:

  • path.join(): Combines path segments using OS-specific separators.
const fullPath = path.join("folder", "subfolder", "app.js");
console.log("Joined Path:", fullPath);
// Output on Windows: folder\subfolder\app.js
// Output on Mac/Linux: folder/subfolder/app.js
  • path.basename(): Gets the filename from a full path.
const filename = path.basename(fullPath);
console.log("Filename:", filename);
// Output: app.js
  • path.extname(): Gets the file extension from a full path.
const extension = path.extname(fullPath);
console.log("File Extension:", extension);
// Output: .js
  • path.dirname(): Gets the directory name from a full path.
const dirname = path.dirname(fullPath);
console.log("Directory Name:", dirname);
// Output: folder/subfolder
  • path.resolve(): Resolves a path into an absolute path.
const absolutePath = path.resolve("folder", "subfolder", "app.js");
console.log("Absolute Path:", absolutePath);
// Output on Windows: C:\folder\subfolder\app.js
// Output on Mac/Linux: /folder/subfolder/app.js
  • path.parse(): Parses a path into an object containing the directory, base, extension, and filename.
const parsedPath = path.parse(fullPath);
console.log("Parsed Path:", parsedPath);
// Output: { root: '', dir: 'folder/subfolder', base: 'app.js', ext: '.js', name: 'app' }

Note : You can use __dirname to get the directory name of the current file and __filename to get the filename of the current file If not using ESM.



Liked This Tutorial

Scan QR Code To Leave A Review Or

Click Here To Leave A Review
Scan QR