path & os Modules
Building portable file paths and reading system information
Skills taught: node.path-module, node.os-module, node.portable-paths
Building paths with the path module
const path = require('path');
// ── Assembling paths ──
console.log(path.join('/home/user', 'projects', 'app', 'index.js'));
// → /home/user/projects/app/index.js
console.log(path.join(__dirname, '..', 'config', 'app.json'));
// → resolves .. relative to __dirname
console.log(path.resolve('src', 'index.js'));
// → absolute: /cwd/src/index.js
// ── Parsing paths ──
const filePath = '/home/user/project/src/main.ts';
console.log('dirname: ', path.dirname(filePath)); // /home/user/project/src
console.log('basename: ', path.basename(filePath)); // main.ts
console.log('no ext: ', path.basename(filePath, '.ts')); // main
console.log('extname: ', path.extname(filePath)); // .ts
console.log('sep: ', JSON.stringify(path.sep)); // '/' on Unix, '\\' on Windows
// ── Parsing to object ──
console.log(path.parse(filePath));
// { root:'/', dir:'/home/user/project/src', base:'main.ts', name:'main', ext:'.ts' }
const os = require('os');
// System information
console.log('Platform: ', os.platform()); // 'linux', 'win32', 'darwin'
console.log('Arch: ', os.arch()); // 'x64', 'arm64'
console.log('Hostname: ', os.hostname());
console.log('Home dir: ', os.homedir());
console.log('Temp dir: ', os.tmpdir());
console.log('EOL char: ', JSON.stringify(os.EOL)); // '\n' (Unix) or '\r\n' (Windows)
// CPU and memory
console.log('CPUs: ', os.cpus().length, 'cores');
console.log('Total RAM: ', (os.totalmem() / 1024**3).toFixed(1), 'GB');
console.log('Free RAM: ', (os.freemem() / 1024**3).toFixed(1), 'GB');
console.log('Uptime: ', (os.uptime() / 3600).toFixed(1), 'hours');
Frequently Asked Questions
What is the difference between path.join() and path.resolve()?
path.join() concatenates segments with the OS separator and normalizes the result, but doesn't make it absolute. path.resolve() processes segments left to right; if a segment is absolute ('/foo'), it discards everything before it. It always returns an absolute path (prepends cwd for relative segments). Use resolve() when you need an absolute path; use join() when assembling path components where the base is already known.