Path & OS Modules

Node.js provide utility modules to interact with the file system paths and the operating system. These are essential for building cross-platform applications.

1. The Path Module

The path module provides utilities for working with file and directory paths. It's crucial because path separators differ between Windows (\\) and Linux/macOS (/).

const path = require('path');

// Join paths correctly for any OS
const fullPath = path.join('users', 'admin', 'config.json');
console.log(fullPath); 
// Windows: users\admin\config.json
// Linux: users/admin/config.json

// Get the base name (filename)
console.log(path.basename('/tmp/secret.txt')); // secret.txt

// Get the extension
console.log(path.extname('index.html')); // .html

// Parse a path into an object
console.log(path.parse('/home/user/dir/file.txt'));

2. The OS Module

The os module provides operating system-related utility methods. You can use it to check memory, CPU details, and system uptime.

const os = require('os');

console.log('Platform:', os.platform()); // win32, linux, darwin
console.log('CPU Architecture:', os.arch()); // x64, arm
console.log('Total Memory:', (os.totalmem() / 1024 / 1024 / 1024).toFixed(2), 'GB');
console.log('Free Memory:', (os.freemem() / 1024 / 1024 / 1024).toFixed(2), 'GB');
console.log('Uptime:', (os.uptime() / 3600).toFixed(2), 'Hours');
console.log('User Info:', os.userInfo());
Use Case: You might use os.cpus().length to determine how many worker threads to spawn in a cluster to maximize performance on a multi-core server.