path & os
Overview
If you build an app on a Mac, folder paths look like this: users/admin/file.txt. If you deploy it to a Windows server, paths look like this: C:\users\admin\file.txt. If you hardcode the slashes in your strings, your app will crash when deployed to a different OS. The built-in path module solves this by mathematically computing secure, OS-agnostic file paths. The os module allows you to probe the physical hardware of the server.
Syntax
const path = require('path');
const os = require('os');
// --- THE PATH MODULE ---
// Safely glues folder names together using the CORRECT slash for the OS
// Mac/Linux: /users/admin/images/avatar.png
// Windows: \users\admin\images\avatar.png
const imagePath = path.join(__dirname, 'images', 'avatar.png');
// Get the actual file name from a massive URL string
console.log(path.basename('/var/www/html/index.html')); // 'index.html'
// Get just the extension
console.log(path.extname('data.json')); // '.json'
// --- THE OS MODULE ---
console.log(os.platform()); // 'darwin', 'win32', 'linux'
console.log(os.totalmem()); // Total RAM in bytes
console.log(os.freemem()); // Available RAM in bytes
console.log(os.cpus()); // Array of CPU core informationCommon Pitfalls
- Using string concatenation for paths (
__dirname + '/images/' + file). This completely breaks cross-platform compatibility. If a Windows server tries to read a path with a forward slash/, it will often fail. ALWAYS usepath.join(). - Vulnerability to Path Traversal attacks. If you let a user download a file by passing a string (e.g.,
req.query.file), they can pass../../../../etc/passwdto steal the server's master password file. Always usepath.normalize()and strictly validate that the resulting path is inside your intended directory.
Interview Questions
path.join() and path.resolve()?path.join() simply glues strings together using the correct OS slash. path.resolve() acts like a sequence of cd commands in the terminal, mathematically evaluating the inputs to generate an absolute, full-disk root path.
Real-World Example
Using the OS module to dynamically spin up exactly enough Node.js worker processes to maximize the server's CPU hardware.
const cluster = require('cluster');
const os = require('os');
// Physically count the number of cores on the server processor
const numCPUs = os.cpus().length;
if (cluster.isPrimary) {
console.log(`Master process is spinning up ${numCPUs} workers...`);
for (let i = 0; i < numCPUs; i++) {
cluster.fork(); // Spawns a new Node.js instance!
}
}Check Your Knowledge
Test your understanding of path & os with these quick questions.