Node.js Built-in Modules
Node.js built-in modules are core functional modules that come with the Node.js runtime and can be used without additional installation. These modules provide basic system functions such as file operations, network communication, and process management, and are fundamental tools for Node.js development.
Unlike third-party modules that need to be installed via npm, built-in modules can be loaded directly through therequire()function, for example:
const http = require('http'); // HTTP module
Introduction to Common Built-in Modules
The following is a detailed description and functional overview of the major built-in modules of Node.js.
| Module Name | Description | Common Classes/Methods | Typical Uses |
|---|---|---|---|
| fs (File System) | File system operations | readFile, writeFile, mkdir, readdir, createReadStream, createWriteStream |
File read/write, directory operations |
| path | Handle file paths | join, resolve, dirname, basename, extname |
Cross-platform path handling |
| http | HTTP server/client | createServer, request, get |
Create web server/client |
| https | HTTPS server/client | createServer, request |
Create secure web services |
| url | URL parsing and handling | parse, format, URLClass |
URL parsing and construction |
| querystring | Query string handling | parse, stringify |
Handle URL query parameters |
| os | Operating system information | cpus, freemem, totalmem, homedir, hostname |
Get system information |
| events | Event handling | EventEmitter, on, emit, once |
Custom event system |
| stream | Stream operations | Readable, Writable, Duplex, Transform, pipe |
Handle data streams |
| crypto | Encryption functionality | createHash, createCipher, createDecipher, randomBytes |
Encryption/decryption/hashing |
| zlib | Compression/decompression | createGzip, createGunzip, createDeflate, createInflate |
Data compression/decompression |
| util | Utility tools | promisify, inherits, format, types |
Utility functions |
| child_process | Child process management | exec, execFile, spawn, fork |
Create child processes |
| cluster | Cluster management | fork, isMaster, isWorker |
Multi-process load balancing |
| dns | Domain name resolution | lookup, resolve, reverse |
Domain name resolution |
| domain | Module for handling errors from multiple asynchronous operations | create , run, add |
Provides a mechanism for grouping multiple different I/O operations and handling their errors uniformly. |
| net | Network operations | createServer, connect, Socket |
TCP server/client |
| dgram | UDP datagram | createSocket, send, bind |
UDP communication |
| readline | Read line by line | createInterface, on('line') |
Command-line interaction |
| repl | Interactive interpreter | start, context |
Create REPL environment |
| vm | Virtual machine | runInContext, createContext, Script |
Execute JavaScript code |
| assert | Assertion testing | equal, strictEqual, deepEqual, throws |
Unit test assertions |
| buffer | Binary data handling | Buffer, alloc, from, concat |
Handle binary data |
| console | Console output | log, error, time, timeEnd |
Debug output |
| timers | Timers | setTimeout, setInterval, setImmediate, clearTimeout |
Scheduled tasks |
| perf_hooks | Performance monitoring | performance, PerformanceObserver |
Performance measurement |
| worker_threads | Worker threads | Worker, isMainThread, parentPort |
Multi-threaded programming |
1. fs (File System Module)
fsThe module provides APIs for interacting with the file system, supporting both synchronous and asynchronous operations.
Main features:
- Read/write files
- Create/delete directories
- Watch file changes
- Get file information
Example code:
Example
// Asynchronously read file
fs.readFile('example.txt', 'utf8', (err, data) => {
if (err) throw err;
console.log(data);
});
// Synchronously write file
try {
fs.writeFileSync('output.txt', 'Hello Node.js');
console.log('File written successfully');
} catch (err) {
console.error(err);
}
2. path (Path Module)
pathThe module provides utility functions for handling file and directory paths, and can be used across platforms.
Common methods:
path.join()- Join pathspath.resolve()- Resolve to absolute pathpath.basename()- Get file namepath.extname()- Get file extension
Example code:
Example
const fullPath = path.join(__dirname, 'files', 'example.txt');
console.log(fullPath); // Output similar to: /home/user/project/files/example.txt
const ext = path.extname('index.html');
console.log(ext); // Output: .html
3. http (HTTP Module)
httpThe module allows Node.js to run as an HTTP server or client.
Main features:
- Create an HTTP server
- Make HTTP requests
- Handle HTTP requests and responses
Example code: Create a simple server
Example
const server = http.createServer((req, res) => {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('Hello Node.js Server');
});
server.listen(3000, () => {
console.log('Server running at http://localhost:3000/');
});
4. events (Events Module)
eventsThe module provides an event-driven programming interface and is the foundation of asynchronous programming in Node.js.
Core concepts:
- EventEmitter class
- Event listening (
on) - Event triggering (
emit)
Example code:
Example
class MyEmitter extends EventEmitter {}
const myEmitter = new MyEmitter();
// Listen for event
myEmitter.on('event', () => {
console.log('Event has been triggered!');
});
// Trigger event
myEmitter.emit('event');
5. os (Operating System Module)
osThe module provides utility methods and properties related to the operating system.
Common features:
- Get CPU information
- Get memory information
- Get network interface information
- Get system temporary directory
Example code:
Example
console.log(os.platform()); // Operating system platform
console.log(os.totalmem()); // Total system memory
console.log(os.freemem()); // Available system memory
console.log(os.cpus()); // CPU information
Other Important Built-in Modules
1. util (Utility Module)
utilThe module provides various utility functions, including:
- Type checking
- Formatting strings
- Converting callback functions to Promises
- Inheritance utilities
2. crypto (Crypto Module)
cryptoThe module provides encryption functionality, including:
- Hash algorithms
- HMAC
- Encryption/decryption
- Digital signatures
3. stream (Stream Module)
streamThe module is an abstract interface for handling streaming data, and many modules in Node.js are implemented based on streams.
4. child_process (Child Process Module)
child_processThe module allows creating and controlling child processes, and can execute system commands or other programs.
5. url (URL Module)
urlThe module provides tools for URL parsing and formatting.
How to Use Built-in Modules
All built-in modules can be loaded directly through therequire()function:
Example
Notes:
- Module names do not need a path
- Module names are case-sensitive
- No installation required, comes with Node.js
- Different Node.js versions may include different built-in modules
Advantages of Built-in Modules
- High performance: Closely integrated with the Node.js runtime
- Stability: Thoroughly tested, high reliability
- No installation required: Works out of the box
- Cross-platform: Consistent behavior across different operating systems
- Comprehensive documentation: Detailed official documentation