When developing backend applications that run on diverse operating systems (Windows development machines, Linux production servers, and macOS laptops), managing file system paths and querying host hardware metrics are essential tasks. Node.js provides the path and os core modules to solve these problems cleanly.
path Module: Cross-Platform File PathsThe path module provides utilities for working with file and directory paths without having to worry about Windows backslashes (\) versus POSIX forward slashes (/).
path.join([...paths])Joins all given path segments using the host operating system's specific separator, and resolves relative segments like . and ..:
const path = require('path');
// Safe, platform-agnostic path joining
const uploadPath = path.join(__dirname, 'public', 'uploads', 'avatars', 'user-123.png');
console.log('Upload Path:', uploadPath);
// On Windows: C:\project\public\uploads\avatars\user-123.png
// On Linux/Mac: /project/public/uploads/avatars/user-123.png
path.resolve([...paths]) vs path.join()// path.resolve creates an absolute path relative to process.cwd()
console.log(path.resolve('static', 'images', 'banner.jpg'));
// Output: G:\Programming\nodejs\static\images\banner.jpg
// If an absolute segment is supplied, resolve restarts from it:
console.log(path.resolve('/data', 'logs', 'error.log'));
// Output on Windows: G:\data\logs\error.log (resolves to drive root)
path.parse(pathString) and path.format(pathObject)Extracts file components into an object containing root, dir, base, ext, and name:
const fileInfo = path.parse('/var/www/veewom/index.html');
console.log(fileInfo);
// {
// root: '/',
// dir: '/var/www/veewom',
// base: 'index.html',
// ext: '.html',
// name: 'index'
// }
os Module: System Hardware InspectionThe os module provides operating-system-related utility methods and properties:
const os = require('os');
console.log('Platform:', os.platform()); // 'win32', 'linux', 'darwin'
console.log('CPU Architecture:', os.arch()); // 'x64', 'arm64'
console.log('Total CPU Cores:', os.cpus().length);
console.log('Total System RAM:', (os.totalmem() / 1024 / 1024 / 1024).toFixed(2), 'GB');
console.log('Free System RAM:', (os.freemem() / 1024 / 1024 / 1024).toFixed(2), 'GB');
console.log('System Uptime:', (os.uptime() / 3600).toFixed(2), 'Hours');
console.log('Home Directory:', os.homedir());
Q: What is the difference between path.basename() and path.extname()?
A: path.basename(path [, ext]) returns the last portion of a path (e.g. 'photo.jpeg'), and can optionally strip the extension if passed as the second argument (path.basename('/img/photo.jpeg', '.jpeg') yields 'photo'). path.extname(path) returns exclusively the file extension including the dot (e.g. '.jpeg').
Boost your server-side JavaScript proficiency by studying these closely connected core modules:
Use path.join with fs.readFile and fs.writeFile safely.
Use os.cpus().length to fork worker processes.
Combine __dirname and path methods.