os, url & Buffers In Practice
9 min read
os, url & Buffers In Practice
Three often-overlooked core modules — os, url, and Buffer — each solve concrete problems. Knowing them saves you from reaching for npm packages unnecessarily.
The os Module
js
const os = require("os");
console.log(os.platform()); // 'linux' | 'darwin' | 'win32'
console.log(os.arch()); // 'x64' | 'arm64'
console.log(os.cpus().length); // number of logical CPU cores
console.log(os.totalmem()); // total RAM in bytes
console.log(os.freemem()); // free RAM in bytes
console.log(os.hostname()); // machine hostname
console.log(os.homedir()); // '/home/alice' or 'C:\Users\Alice'
console.log(os.tmpdir()); // '/tmp'
console.log(os.EOL); // '\n' on Unix, '\r\n' on WindowsThe url Module & WHATWG URL
Since Node.js 10, the WHATWG `URL` class is available globally (no import needed) and is the preferred way to parse and construct URLs. It matches the browser API exactly.
js
const endpoint = new URL("https://api.example.com/users?page=2&limit=20");
console.log(endpoint.hostname); // api.example.com
console.log(endpoint.pathname); // /users
console.log(endpoint.searchParams.get("page")); // '2'
console.log(endpoint.searchParams.get("limit")); // '20'
// Mutate and reconstruct
endpoint.searchParams.set("page", "3");
console.log(endpoint.toString());
// https://api.example.com/users?page=3&limit=20
// urlencoded body parsing (Node.js 10+)
const params = new URLSearchParams("name=Alice&role=admin");
console.log(params.get("name")); // AliceBuffers — Binary Data In Detail
js
// Buffers are Uint8Array subclasses — fixed-size raw memory
const buf = Buffer.alloc(8, 0); // 8 zero bytes
buf.writeUInt32BE(1234567890, 0); // write 4-byte big-endian int at offset 0
buf.writeUInt32LE(9876543210 >>> 0, 4); // write 4-byte little-endian int at offset 4
console.log(buf.readUInt32BE(0)); // 1234567890
// Encoding / decoding
const encoded = Buffer.from("hello world", "utf8").toString("base64");
console.log(encoded); // aGVsbG8gd29ybGQ=
const decoded = Buffer.from(encoded, "base64").toString("utf8");
console.log(decoded); // hello world
// Comparing and concatenating
const a = Buffer.from([1, 2, 3]);
const b = Buffer.from([4, 5, 6]);
const combined = Buffer.concat([a, b]);
console.log([...combined]); // [1, 2, 3, 4, 5, 6]Use Buffer.alloc(n) (zero-filled) instead of the deprecated new Buffer(n). For sensitive data such as keys and tokens, call buffer.fill(0) to zero the memory before discarding the buffer.
Ready to test yourself?
Practice Node.js— quiz & coding exercises