Node.js provides a rich library of built-in modules that can be used without any additional installation. These modules form the core functionality of Node.js and are designed to perform a wide variety of essential tasks such as file system operations, networking, cryptography, buffer handling, stream management, and much more. Understanding how to use these built-in modules is vital for any developer working with Node.js and NPM (Node Package Manager).
Built-in modules are also known as core modules. They are compiled into the Node.js binary and are part of the Node.js runtime environment. As such, they can be used in any Node.js application without being explicitly installed via NPM.
To use a built-in module, you simply require it using the `require()` function. These modules provide functionality that covers a broad range of server-side use cases.
const fs = require('fs');
const http = require('http');
In the above example, we are using the built-in `fs` (File System) and `http` (HTTP server) modules.
Here is a list of some of the most commonly used built-in modules in Node.js:
The `fs` module allows you to work with the file system. You can read, write, delete, and perform many other file-related operations.
const fs = require('fs');
fs.readFile('example.txt', 'utf8', (err, data) => {
if (err) {
console.error(err);
return;
}
console.log(data);
});
fs.writeFile('output.txt', 'Hello, Node.js!', (err) => {
if (err) {
console.error(err);
return;
}
console.log('File written successfully!');
});
The `http` module allows you to create web servers and handle HTTP requests and responses.
const http = require('http');
const server = http.createServer((req, res) => {
res.statusCode = 200;
res.setHeader('Content-Type', 'text/plain');
res.end('Hello, World!');
});
server.listen(3000, () => {
console.log('Server is running on port 3000');
});
The `path` module provides utilities for working with file and directory paths. It is especially useful when building file paths that work across different operating systems.
const path = require('path');
const fullPath = path.join(__dirname, 'folder', 'file.txt');
console.log(fullPath);
const ext = path.extname('index.html');
console.log(ext); // .html
The `os` module provides operating system-related utility methods and properties.
const os = require('os');
console.log('Platform:', os.platform());
console.log('CPU Architecture:', os.arch());
console.log('Total Memory:', os.totalmem());
console.log('Free Memory:', os.freemem());
The `url` module is used for URL resolution and parsing.
const url = require('url');
const parsedUrl = url.parse('https://example.com/path?name=John');
console.log(parsedUrl.hostname); // example.com
console.log(parsedUrl.query); // name=John
The `events` module allows you to handle custom events and is the foundation of the event-driven architecture in Node.js.
const EventEmitter = require('events');
const emitter = new EventEmitter();
emitter.on('greet', () => {
console.log('Hello from event!');
});
emitter.emit('greet');
The `stream` module provides APIs for working with streaming data. There are four types of streams: readable, writable, duplex, and transform.
const fs = require('fs');
const readStream = fs.createReadStream('example.txt', 'utf8');
readStream.on('data', (chunk) => {
console.log(chunk);
});
The `crypto` module provides cryptographic functionality that includes a set of wrappers for OpenSSLβs hash, HMAC, cipher, decipher, sign, and verify functions.
const crypto = require('crypto');
const hash = crypto.createHash('sha256').update('Hello').digest('hex');
console.log(hash);
The `util` module provides various utility functions. It is often used for debugging and inheritance.
const util = require('util');
console.log(util.format('%s:%s', 'foo', 'bar'));
The `querystring` module provides utilities for parsing and formatting URL query strings.
const querystring = require('querystring');
const parsed = querystring.parse('name=John&age=25');
console.log(parsed.name); // John
The `zlib` module provides compression functionality using the Gzip and Deflate algorithms.
const zlib = require('zlib');
const fs = require('fs');
const gzip = zlib.createGzip();
const input = fs.createReadStream('example.txt');
const output = fs.createWriteStream('example.txt.gz');
input.pipe(gzip).pipe(output);
Often, you will use multiple modules together to build a feature-rich application. Here's an example that combines `http`, `fs`, and `path` to serve static files.
const http = require('http');
const fs = require('fs');
const path = require('path');
const server = http.createServer((req, res) => {
let filePath = path.join(__dirname, req.url === '/' ? 'index.html' : req.url);
const ext = path.extname(filePath);
let contentType = 'text/html';
if (ext === '.js') contentType = 'text/javascript';
else if (ext === '.css') contentType = 'text/css';
fs.readFile(filePath, (err, content) => {
if (err) {
res.writeHead(500);
res.end('Server Error');
} else {
res.writeHead(200, { 'Content-Type': contentType });
res.end(content, 'utf-8');
}
});
});
server.listen(3000, () => {
console.log('Server running at http://localhost:3000/');
});
Node.js built-in modules are powerful tools that allow developers to build robust and efficient applications without the need to install third-party packages. They offer foundational capabilities such as file handling, server creation, data compression, and cryptography. By mastering these core modules, developers can not only write cleaner code but also reduce external dependencies, leading to more secure and performant applications. Understanding how to use and combine built-in modules is a critical step in becoming an effective Node.js developer.
A function passed as an argument and executed later.
Runs multiple instances to utilize multi-core systems.
Reusable blocks of code, exported and imported using require() or import.
nextTick() executes before setImmediate() in the event loop.
Starts a server and listens on specified port.
Node Package Manager β installs, manages, and shares JavaScript packages.
A minimal and flexible web application framework for Node.js.
A stream handles reading or writing data continuously.
It processes asynchronous callbacks and non-blocking I/O operations efficiently.
Node.js is a JavaScript runtime built on Chrome's V8 engine for server-side scripting.
An object representing the eventual completion or failure of an asynchronous operation.
require is CommonJS; import is ES6 syntax (requires transpilation or newer versions).
Use module.exports or exports.functionName.
Variables stored outside the code for configuration, accessed using process.env.
MongoDB, often used with Mongoose for schema management.
Describes project details and manages dependencies and scripts.
Synchronous blocks execution; asynchronous runs in background without blocking.
Allows or restricts resources shared between different origins.
Use try-catch, error events, or middleware for error handling.
Provides file system-related operations like read, write, delete.
Using event-driven architecture and non-blocking I/O.
Functions in Express that execute during request-response cycle.
A set of routes or endpoints to interact with server logic or databases.
Yes, it's single-threaded but handles concurrency using the event loop and asynchronous callbacks.
Middleware to parse incoming request bodies, like JSON or form data.
Copyrights © 2024 letsupdateskills All rights reserved