Core modules tour
Overview
Node comes with a standard library: dozens of built-in modules for files, networking, processes, cryptography and more. They’re installed with Node, maintained by the Node.js team, and need no npm install.
You’ll study the big ones — fs, stream, http, events, child_process — in their own topics. This topic tours the smaller utilities you’ll reach for again and again.
Importing built-ins
import os from 'node:os'; // whole module
import { readFile } from 'node:fs/promises'; // promise-based API
import { setTimeout as sleep } from 'node:timers/promises';
import { randomUUID } from 'node:crypto';Always use the node: prefix. It makes clear the module is built in, it can’t be confused with an npm package of the same name, and it loads slightly faster.
Many older modules have a promise version at a sub-path — node:fs/promises, node:timers/promises, node:dns/promises, node:readline/promises, node:stream/promises. Prefer these; they work naturally with await.
os — the machine you’re running on
import os from 'node:os';
os.platform(); // 'linux', 'darwin' (macOS) or 'win32'
os.arch(); // 'x64', 'arm64'
os.availableParallelism(); // how many things can run in parallel (≈ CPU cores)
os.totalmem(); // bytes of RAM
os.freemem();
os.homedir(); // '/home/asha'
os.tmpdir(); // a temp folder you can write to
os.hostname();
os.EOL; // '\n' on macOS/Linux, '\r\n' on WindowsYou’ll use availableParallelism() when deciding how many worker processes to start, and tmpdir() for temporary files.
path — working with file paths
Paths differ between operating systems (/ on macOS and Linux, \ on Windows). The path module builds them correctly everywhere:
import path from 'node:path';
path.join('uploads', 'avatars', 'asha.png'); // 'uploads/avatars/asha.png'
path.extname('photo.jpeg'); // '.jpeg'The next chapter covers path in depth.
util — handy helpers
import util from 'node:util';
// Turn a callback-style function into one that returns a promise
import { pbkdf2 } from 'node:crypto';
const pbkdf2Async = util.promisify(pbkdf2);
// Inspect deeply nested objects (console.log stops at depth 2)
console.log(util.inspect(bigObject, { depth: null, colors: true }));
// Compare deeply
util.isDeepStrictEqual({ a: [1, 2] }, { a: [1, 2] }); // true
// Format strings printf-style
util.format('%s has %d items', 'cart', 3); // 'cart has 3 items'util.parseArgs parses command-line flags without any npm package:
import { parseArgs } from 'node:util';
const { values } = parseArgs({
options: {
port: { type: 'string', short: 'p', default: '3000' },
verbose: { type: 'boolean', short: 'v' },
},
});
// node app.js -p 8080 --verbose → { port: '8080', verbose: true }util.styleText adds colour to terminal output: console.log(util.styleText('green', 'Done!')).
crypto — randomness and hashing
import { randomUUID, randomBytes, createHash, randomInt } from 'node:crypto';
randomUUID(); // 'f3b7c2d4-…' — unique IDs
randomBytes(32).toString('hex'); // a secure random token
randomInt(1, 7); // a secure dice roll, 1–6
createHash('sha256').update('hello').digest('hex'); // a fingerprint of some datanode:crypto is cryptographically secure — use it, not Math.random(), for tokens, IDs and anything security-related. Password hashing has its own topic later.
timers/promises — waiting with await
import { setTimeout as sleep, setInterval } from 'node:timers/promises';
await sleep(500); // pause this async function for half a second
for await (const _ of setInterval(1000)) {
console.log('tick'); // every second, until you break
}Retrying with a delay becomes very readable:
for (let attempt = 1; attempt <= 3; attempt++) {
try {
return await connect();
} catch (err) {
if (attempt === 3) throw err;
await sleep(attempt * 1000);
}
}readline — asking questions in the terminal
import * as readline from 'node:readline/promises';
import { stdin as input, stdout as output } from 'node:process';
const rl = readline.createInterface({ input, output });
const name = await rl.question('What is your name? ');
console.log(`Welcome, ${name}!`);
rl.close();readline can also read a file line by line, which you’ll use with streams later.
Others worth knowing
| Module | Use it to… |
|---|---|
node:url |
parse and build URLs, convert file URLs to paths |
node:zlib |
gzip/brotli compress and decompress |
node:assert |
check assumptions; the basis of tests |
node:test |
write and run tests (no Jest needed) |
node:dns |
look up domain names |
node:net |
raw TCP servers and clients |
node:perf_hooks |
measure performance precisely |
node:sqlite |
a built-in SQLite database (newer releases) |
Before installing a package, check the built-ins. UUIDs, argument parsing, coloured output, deep equality, testing, file watching and
fetchused to need npm packages. Now they’re all part of Node. Fewer dependencies means fewer security updates and faster installs.
A system report
Write report.js that prints: the platform, the number of CPU cores, total memory in GB (1 decimal place), how long the machine has been up in hours, and a random UUID as a report ID.
import os from 'node:os';
// your code hereimport os from 'node:os';
import { randomUUID } from 'node:crypto';
const gb = (bytes) => (bytes / 1024 ** 3).toFixed(1);
console.log({
reportId: randomUUID(),
platform: `${os.platform()} ${os.arch()}`,
cpus: os.availableParallelism(),
memoryGB: gb(os.totalmem()),
freeGB: gb(os.freemem()),
uptimeHours: (os.uptime() / 3600).toFixed(1),
});Summary
- Node ships with a standard library of modules — no install needed.
- Import them with the
node:prefix; many have promise versions (node:fs/promises,node:timers/promises). os,path,util,cryptoandreadlineare useful in almost every project.util.promisifyconverts old callback APIs;util.inspectandutil.parseArgshelp with debugging and CLIs.- Check the built-ins before reaching for an npm package.