Path and OS Modules
File paths and operating system resources differ greatly between platforms (such as Windows, macOS, and Linux). Node.js provides two utility modules, path and os, to normalize path processing and expose hardware details.
1. Cross-Platform Path Handling with path
Operating systems use different segment separators (backslash \ on Windows, forward slash / on macOS/Linux). Hardcoding these in your code will result in cross-platform failures.
The path module solves this problem dynamically.
Essential path Functions
import path from "path";
// 1. Join path segments together using the platform-specific separator
const dirPath = path.join("users", "admin", "documents");
console.log("Joined Path:", dirPath); // Windows: users\admin\documents, Posix: users/admin/documents
// 2. Resolve segments into an absolute path (from current working directory)
const absPath = path.resolve("src", "config", "settings.json");
console.log("Absolute Path:", absPath);
// 3. Extract the last segment of a path (filename)
const file = path.basename("/var/log/app.log");
console.log("Basename:", file); // Outputs: app.log
// 4. Extract the extension of a file
const ext = path.extname("index.html");
console.log("Extension:", ext); // Outputs: .html
// 5. Parse a path into an object containing all individual components
const parsed = path.parse("C:\\projects\\app\\package.json");
console.log("Parsed Path Object:", parsed);2. Retrieving Hardware Information with os
The os module exposes metrics from the host operating system, which is helpful for sizing thread pools, monitoring memory consumption, and checking system health.
import os from "os";
// 1. Get system CPU core details
const cpus = os.cpus();
console.log("CPU Cores:", cpus.length);
console.log("CPU Model Name:", cpus[0].model);
// 2. Get total and free memory
const totalMemBytes = os.totalmem();
const freeMemBytes = os.freemem();
console.log("Total System Memory:", (totalMemBytes / 1024 / 1024 / 1024).toFixed(2), "GB");
console.log("Free System Memory:", (freeMemBytes / 1024 / 1024 / 1024).toFixed(2), "GB");
// 3. Get platform architecture details
console.log("Platform:", os.platform()); // win32, darwin, linux
console.log("Architecture:", os.arch()); // x64, arm64
// 4. Get current user home directory
console.log("User Home Dir:", os.homedir());3. Real-World Application: System Resource Monitor
Here is a short utility script that logs host details and triggers alerts if system resources run low:
import os from "os";
function monitorSystem() {
const freeMemPercent = (os.freemem() / os.totalmem()) * 100;
const loadAverage = os.loadavg(); // Returns load averages for 1, 5, and 15 minutes (Unix only)
console.log(`System Status Monitor`);
console.log(`Free Memory Ratio: ${freeMemPercent.toFixed(1)}%`);
console.log(`1 Min CPU Load Average: ${loadAverage[0].toFixed(2)}`);
if (freeMemPercent < 15) {
console.warn("WARNING: Available system memory is running critically low!");
}
}
// Check system stats
monitorSystem();Published on Last updated: