Node.js Masterclass
High-Performance Backends01.Home02.Introduction03.Environment Setup04.Modules & Exports05.File System (fs)06.Path & OS Modules07.Buffer & Streams08.Events & EventEmitter09.HTTP Module10.NPM & Package.json11.Express.js Fundamentals12.Express Routing13.Express Middleware14.RESTful API Development15.Asynchronous Programming16.Error Handling17.Database with Mongoose18.Authentication with JWT19.Environment Variables20.Testing with Jest21.Deployment & PM2
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.