Node.js5 min read

Path Module Essentials

Learn to work with file paths correctly in Node.js using the path module. Cross-platform path handling.

Sarah Chen
December 19, 2025
0.0k0

Path Module Essentials

The path module handles file paths. Essential for cross-platform code.

Why Use path?

// ❌ Hardcoded - breaks on Windows
const file = '/users/data/' + 'file.txt';

// ✅ Cross-platform
const file = path.join('/users/data', 'file.txt');

Import

const path = require('path');

path.join() - Combine Paths

path.join('folder', 'subfolder', 'file.txt');
// → 'folder/subfolder/file.txt' (Unix)
// → 'folder\\subfolder\\file.txt' (Windows)

path.join(__dirname, 'data', 'config.json');
// → '/app/project/data/config.json'

path.resolve() - Absolute Path

path.resolve('file.txt');
// → '/current/working/directory/file.txt'

path.resolve('/foo', 'bar', 'baz');
// → '/foo/bar/baz'

path.resolve('foo', '/bar', 'baz');
// → '/bar/baz' (starts fresh from /bar)

path.basename() - File Name

path.basename('/path/to/file.txt');
// → 'file.txt'

path.basename('/path/to/file.txt', '.txt');
// → 'file' (without extension)

path.dirname() - Directory

path.dirname('/path/to/file.txt');
// → '/path/to'

path.extname() - Extension

path.extname('file.txt');      // → '.txt'
path.extname('file.tar.gz');   // → '.gz'
path.extname('file');          // → ''

path.parse() - Break Down Path

path.parse('/home/user/file.txt');
// {
//   root: '/',
//   dir: '/home/user',
//   base: 'file.txt',
//   ext: '.txt',
//   name: 'file'
// }

path.format() - Build Path

path.format({
  dir: '/home/user',
  name: 'file',
  ext: '.txt'
});
// → '/home/user/file.txt'

__dirname and __filename

// Current file's directory
console.log(__dirname);   // '/app/project/src'

// Current file's full path
console.log(__filename);  // '/app/project/src/app.js'

// Common pattern
const dataPath = path.join(__dirname, '..', 'data', 'config.json');

Practical Example

const path = require('path');
const fs = require('fs').promises;

async function processFiles(directory) {
  const files = await fs.readdir(directory);
  
  for (const file of files) {
    const fullPath = path.join(directory, file);
    const ext = path.extname(file);
    
    if (ext === '.txt') {
      console.log(`Processing: ${path.basename(file)}`);
      // Process file...
    }
  }
}

processFiles(path.join(__dirname, 'data'));

Key Takeaway

Always use path.join() to combine paths - never concatenate strings. Use __dirname for paths relative to your file. The path module ensures your code works on any operating system.

#Node.js#Path#File System#Beginner