# Path & OS Modules

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

Canonical: https://www.internhack.in/learn/interview/nodejs-interview/node-path-os
Last updated: 2026-11-28

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

- Never concatenate paths with + and '/' - always use path.join()
- path.resolve() returns an absolute path; path.join() preserves relativity
- os.cpus().length is commonly used to determine worker/cluster count
- On Windows, path.sep is '\\\\' while on Unix it is '/'

## Common follow-up questions

- How does path.resolve differ from path.join?
- How would you use os.cpus() to optimize a Node.js application?

## Interview tips

- Emphasize cross-platform compatibility as the main reason to use the path module
- Mention path.join vs path.resolve - interviewers often ask the difference
- Show practical usage like building config paths or determining system resources

## Concepts covered

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

Previous: [File System Operations](https://www.internhack.in/learn/interview/nodejs-interview/node-fs-operations) · Next: [HTTP Module & Server Creation](https://www.internhack.in/learn/interview/nodejs-interview/node-http-server) · [All of Node.js Interview](https://www.internhack.in/learn/interview/nodejs-interview)

## More Node.js Interview questions

- [Express.js Fundamentals](https://www.internhack.in/learn/interview/nodejs-interview/node-express-fundamentals)
- [Routing & Route Parameters](https://www.internhack.in/learn/interview/nodejs-interview/node-routing-params)
- [Middleware Deep Dive](https://www.internhack.in/learn/interview/nodejs-interview/node-middleware-deep-dive)
- [Request Validation (Zod/Joi)](https://www.internhack.in/learn/interview/nodejs-interview/node-request-validation)
- [JWT Authentication](https://www.internhack.in/learn/interview/nodejs-interview/node-jwt-auth)
- [Password Hashing (bcrypt)](https://www.internhack.in/learn/interview/nodejs-interview/node-password-hashing)

## Related

- [Learn](https://www.internhack.in/learn)
- [Interview Prep](https://www.internhack.in/learn/interview)
- [Node.js Interview](https://www.internhack.in/learn/interview/nodejs-interview)
