Built-in Node.js Modules
Node.js comes with a rich set of built-in modules that provide essential functionality without installing any packages. These core modules are stable, well-documented, and optimized for performance.
Overview of Built-in Modules
Node.js includes over 30 built-in modules. Here are the most commonly used:
| Module | Purpose |
|---|---|
fs | File system operations |
path | File path utilities |
http / https | HTTP servers and clients |
url | URL parsing |
os | Operating system info |
events | Event emitter pattern |
util | Utility functions |
crypto | Cryptography |
stream | Streaming data |
buffer | Binary data handling |
Let's explore the most important ones!
The path Module
The path module helps you work with file and directory paths safely across different operating systems.
const path = require('path');
// Join path segments
const fullPath = path.join('/users', 'john', 'documents', 'file.txt');
// Result: /users/john/documents/file.txt (Unix)
// Result: \users\john\documents\file.txt (Windows)
// Get filename
path.basename('/path/to/file.txt'); // 'file.txt'
path.basename('/path/to/file.txt', '.txt'); // 'file'
// Get directory
path.dirname('/path/to/file.txt'); // '/path/to'
// Get extension
path.extname('image.png'); // '.png'
// Resolve to absolute path
path.resolve('src', 'utils', 'helper.js');
// Result: /current/working/dir/src/utils/helper.js
// Parse path into components
path.parse('/home/user/file.txt');
// { root: '/', dir: '/home/user', base: 'file.txt', ext: '.txt', name: 'file' }
The os Module
The os module provides operating system information:
const os = require('os');
// Platform and architecture
console.log(os.platform()); // 'darwin', 'win32', 'linux'
console.log(os.arch()); // 'x64', 'arm64'
// User info
console.log(os.homedir()); // '/Users/john'
console.log(os.hostname()); // 'johns-macbook'
console.log(os.userInfo().username);
// System resources
console.log(os.cpus().length); // Number of CPU cores
console.log(os.totalmem()); // Total memory in bytes
console.log(os.freemem()); // Free memory in bytes
// Uptime
console.log(os.uptime()); // System uptime in seconds
// Network interfaces
console.log(os.networkInterfaces());
// End of line character
console.log(os.EOL); // '\n' on Unix, '\r\n' on Windows
The url Module
The url module helps parse and format URLs:
const url = require('url');
// Parse a URL (Legacy API)
const parsed = url.parse('https://example.com:8080/path?query=value#hash');
console.log(parsed.hostname); // 'example.com'
console.log(parsed.port); // '8080'
console.log(parsed.pathname); // '/path'
console.log(parsed.query); // 'query=value'
// Modern URL API (preferred)
const myUrl = new URL('https://example.com:8080/path?name=john&age=30');
console.log(myUrl.hostname); // 'example.com'
console.log(myUrl.port); // '8080'
console.log(myUrl.pathname); // '/path'
console.log(myUrl.searchParams.get('name')); // 'john'
console.log(myUrl.searchParams.get('age')); // '30'
// Build URLs
const newUrl = new URL('https://api.example.com');
newUrl.pathname = '/users';
newUrl.searchParams.set('page', '1');
newUrl.searchParams.set('limit', '10');
console.log(newUrl.toString());
// 'https://api.example.com/users?page=1&limit=10'
The crypto Module
The crypto module provides cryptographic functionality:
const crypto = require('crypto');
// Generate random bytes
const randomBytes = crypto.randomBytes(16).toString('hex');
console.log(randomBytes); // 'a3b5c7d9e1f2a4b6c8d0e2f4a6b8c0d2'
// Generate UUID
const uuid = crypto.randomUUID();
console.log(uuid); // 'f47ac10b-58cc-4372-a567-0e02b2c3d479'
// Hash a password
const hash = crypto.createHash('sha256')
.update('myPassword123')
.digest('hex');
console.log(hash);
// HMAC for API signatures
const hmac = crypto.createHmac('sha256', 'secretKey')
.update('message to sign')
.digest('hex');
console.log(hmac);
The util Module
The util module provides useful utility functions:
const util = require('util');
// Format strings (like printf)
const formatted = util.format('%s has %d items', 'Cart', 5);
console.log(formatted); // 'Cart has 5 items'
// Inspect objects (for debugging)
const obj = { a: 1, b: { c: 2, d: { e: 3 } } };
console.log(util.inspect(obj, { depth: null, colors: true }));
// Promisify callback-based functions
const fs = require('fs');
const readFile = util.promisify(fs.readFile);
async function read() {
const content = await readFile('file.txt', 'utf8');
console.log(content);
}
// Deprecate functions
const oldFunction = util.deprecate(() => {
console.log('Old implementation');
}, 'oldFunction is deprecated, use newFunction instead');
The events Module
The events module provides the EventEmitter class for event-driven programming:
const EventEmitter = require('events');
// Create an emitter
const emitter = new EventEmitter();
// Listen for events
emitter.on('userLoggedIn', (user) => {
console.log(`Welcome, ${user.name}!`);
});
emitter.on('userLoggedIn', (user) => {
console.log(`Logging activity for ${user.email}`);
});
// Emit events
emitter.emit('userLoggedIn', { name: 'John', email: 'john@example.com' });
// Output:
// Welcome, John!
// Logging activity for john@example.com
// Listen once
emitter.once('connect', () => {
console.log('Connected! This only runs once.');
});
// Remove listeners
const handler = () => console.log('Handler');
emitter.on('event', handler);
emitter.off('event', handler);
The buffer Module
Buffers handle binary data:
const buffer = require('buffer');
// Create buffers
const buf1 = Buffer.from('Hello');
const buf2 = Buffer.alloc(10); // 10 zero-filled bytes
const buf3 = Buffer.allocUnsafe(10); // 10 uninitialized bytes (faster)
// Convert between formats
const str = buf1.toString('utf8');
const hex = buf1.toString('hex');
const base64 = buf1.toString('base64');
console.log(str); // 'Hello'
console.log(hex); // '48656c6c6f'
console.log(base64); // 'SGVsbG8='
// Buffer operations
buf1.length; // 5
buf1[0]; // 72 (ASCII for 'H')
Buffer.concat([buf1, Buffer.from(' World')]);
Practical Example: System Info Tool
Importing Built-in Modules
Both CommonJS and ES Module syntax work:
// CommonJS
const fs = require('fs');
const path = require('path');
// ES Modules
import fs from 'fs';
import path from 'path';
// ES Modules with node: prefix (recommended for clarity)
import fs from 'node:fs';
import path from 'node:path';
The node: prefix makes it clear you're importing a built-in module, not a package.
Key Takeaways
- Node.js includes many built-in modules—no npm install needed
pathhandles file paths safely across operating systemsosprovides system information (CPU, memory, platform)urlandURLclass parse and build URLscryptoprovides cryptographic functions (hashing, encryption, UUIDs)utiloffers utilities like promisify and formateventsprovides EventEmitter for event-driven programming- Use
node:prefix to clearly indicate built-in modules
Summary
Node.js's built-in modules provide essential functionality for server-side development. You've learned about the most important ones: path manipulation, system information, URL handling, cryptography, and event-driven programming. These modules form the foundation of Node.js development and are used extensively in real-world applications.
Next, we'll dive deep into the file system module and learn how to read, write, and manage files and directories.

