Loading lessons...
Core Built-In Modules: os, path, and url
Essential Node.js Core Modules
Node.js comes with a comprehensive suite of built-in utility modules. No npm installation is required.
1. The os Module (Operating System Information)
const os = require("node:os");
console.log("Platform:", os.platform()); // 'win32', 'darwin', 'linux'
console.log("CPU Cores:", os.cpus().length);
console.log("Total Memory (GB):", (os.totalmem() / 1024**3).toFixed(2));
console.log("Free Memory (GB):", (os.freemem() / 1024**3).toFixed(2));
console.log("User Home Dir:", os.homedir());
2. The path Module (File and Directory Paths)
Handles cross-platform file paths cleanly regardless of OS slashes (/ vs \).
const path = require("node:path");
const fullPath = path.join(__dirname, "uploads", "images", "photo.png");
console.log("Joined Path:", fullPath);
const parsed = path.parse(fullPath);
console.log("Ext name:", parsed.ext); // '.png'
console.log("Base name:", parsed.base); // 'photo.png'
const normalized = path.normalize("/users/admin/../guest/file.txt");
console.log(normalized); // '/users/guest/file.txt'
3. The url Module (URL Parsing)
const { URL } = require("node:url");
const myUrl = new URL("https://api.example.com:8080/v1/users?role=admin&page=2#active");
console.log("Hostname:", myUrl.hostname); // 'api.example.com'
console.log("Port:", myUrl.port); // '8080'
console.log("Pathname:", myUrl.pathname); // '/v1/users'
console.log("Query Role:", myUrl.searchParams.get("role")); // 'admin'
TL;DR
- Use
node:prefix (e.g.require('node:path')) for core built-ins. path.join()builds safe cross-platform file system paths.new URL()parses query parameters and URL components cleanly.