#1 Data Analytics Program in India
₹2,499₹1,499Enroll Now
3 min read
Question 10 of 62easy

How to use the Path module in Node.js?

Working with file and directory paths.

What You'll Learn

  • Path manipulation methods
  • Cross-platform path handling
  • Common patterns

Path Module Methods

code.jsJavaScript
const path = require('path');

// Join paths (cross-platform)
path.join('/users', 'john', 'docs');
// /users/john/docs (Unix)
// \users\john\docs (Windows)

// Resolve absolute path
path.resolve('src', 'index.js');
// /current/working/dir/src/index.js

// Get directory name
path.dirname('/users/john/file.txt');
// /users/john

// Get file name
path.basename('/users/john/file.txt');
// file.txt
path.basename('/users/john/file.txt', '.txt');
// file

// Get extension
path.extname('file.txt');
// .txt

// Parse path
path.parse('/users/john/file.txt');
// { root: '/', dir: '/users/john', base: 'file.txt', ext: '.txt', name: 'file' }

// Format path object to string
path.format({ dir: '/users', base: 'file.txt' });
// /users/file.txt

Common Patterns

code.jsJavaScript
// Get current file's directory
const currentDir = path.dirname(__filename);

// Build path relative to current file
const configPath = path.join(__dirname, 'config.json');

// Normalize path (removes extra slashes)
path.normalize('/users//john/../jane/');
// /users/jane