Path & OS Modules

Difficulty: Beginner

Question

How do you handle file paths and OS information in Node.js? Why is the path module important for cross-platform code?

Answer

The path module provides utilities for working with file and directory paths in a cross-platform way. Different operating systems use different path separators (/ on Unix, \ on Windows), and the path module abstracts these differences.

path.join() combines path segments using the correct separator. path.resolve() creates absolute paths. path.basename(), path.dirname(), and path.extname() extract parts of a path. Never use string concatenation for paths.

The os module provides operating system information like CPU architecture, total memory, network interfaces, hostname, and the current user's home directory. It is useful for system monitoring, generating system reports, and writing platform-aware code.

Both modules are built-in and require no installation. They are fundamental to any Node.js application that deals with files or needs to adapt behavior based on the host system.

Code examples

Path Module Essentials

const path = require('path');

// Join path segments (handles separators)
const filePath = path.join('/users', 'john', 'docs', 'report.pdf');
console.log(filePath);

// Resolve to absolute path
const abs = path.resolve('src', 'utils', 'helper.js');
console.log(abs);

// Extract path components
console.log(path.basename('/users/john/photo.png'));     // photo.png
console.log(path.basename('/users/john/photo.png', '.png')); // photo
console.log(path.dirname('/users/john/photo.png'));      // /users/john
console.log(path.extname('/users/john/photo.png'));      // .png

// Parse a full path
const parsed = path.parse('/users/john/photo.png');
console.log(parsed);

path.join handles separators correctly across OS. path.resolve creates absolute paths from the current directory. parse() breaks a path into all its components.

OS Module for System Information

const os = require('os');

console.log('Platform:', os.platform());   // linux, darwin, win32
console.log('Architecture:', os.arch());   // x64, arm64
console.log('CPUs:', os.cpus().length);
console.log('Total Memory:', (os.totalmem() / 1024 / 1024 / 1024).toFixed(1) + ' GB');
console.log('Free Memory:', (os.freemem() / 1024 / 1024 / 1024).toFixed(1) + ' GB');
console.log('Home Dir:', os.homedir());
console.log('Temp Dir:', os.tmpdir());
console.log('Hostname:', os.hostname());
console.log('Uptime:', (os.uptime() / 3600).toFixed(1) + ' hours');

// Network interfaces
const nets = os.networkInterfaces();
for (const [name, addrs] of Object.entries(nets)) {
  for (const addr of addrs) {
    if (addr.family === 'IPv4' && !addr.internal) {
      console.log(`${name}: ${addr.address}`);
    }
  }
}

The os module is useful for health checks, monitoring dashboards, and making platform-specific decisions in your application.

Cross-Platform Path Handling

const path = require('path');

// BAD: hardcoded separator - breaks on Windows
const bad = '/users/' + username + '/config.json';

// GOOD: path.join handles OS differences
const good = path.join('/users', username, 'config.json');

// Normalize messy paths
console.log(path.normalize('/users//john/../jane/docs'));
// Output: /users/jane/docs

// Check if path is absolute
console.log(path.isAbsolute('/etc/config'));  // true
console.log(path.isAbsolute('./config'));     // false

// Relative path between two locations
console.log(path.relative(
  '/users/john/projects',
  '/users/john/documents/report.pdf'
));
// Output: ../documents/report.pdf

// Common pattern: resolve from project root
const projectRoot = path.resolve(__dirname, '..');
const configPath = path.join(projectRoot, 'config', 'default.json');

Always use path methods instead of string concatenation. normalize cleans up double slashes and resolves .. segments.

Key points

Concepts covered

path module, os module, cross-platform, path.join