In this article, we will explore different Core In-Built Modules of Node.js.
List of Core In-Built Modules of Node.js
Node.js comes with a set of core modules that are built-in and available for use without the need for additional installation. These modules provide fundamental functionalities for various tasks. Here are some of the key core built-in Node.js modules:
fs (File System)
Provides file system-related operations, such as reading and writing to files, creating directories, and handling file metadata.
const fs = require('fs');
// Reading a file asynchronously
fs.readFile('example.txt', 'utf8', (err, data) => {
if (err) throw err;
console.log(data);
});
// Writing to a file asynchronously
fs.writeFile('example.txt', 'Hello, Node.js!', 'utf8', (err) => {
if (err) throw err;
console.log('File has been written.');
});
http and https
Facilitate the creation of HTTP and HTTPS servers. These modules are essential for handling web requests and responses.
const http = require('http');
// Creating a simple HTTP server
const server = http.createServer((req, res) => {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('Hello, Node.js HTTP Server!\n');
});
// Listening on port 3000
server.listen(3000, '127.0.0.1', () => {
console.log('Server listening on port 3000');
});
const https = require('https');
const fs = require('fs');
// Read SSL/TLS certificate and key
const options = {
key: fs.readFileSync('private-key.pem'),
cert: fs.readFileSync('public-certificate.pem')
};
// Creating an HTTPS server
const server = https.createServer(options, (req, res) => {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('Hello, Node.js HTTPS Server!\n');
});
// Listening on port 443 (default for HTTPS)
server.listen(443, () => {
console.log('HTTPS Server listening on port 443');
});
path
Offers utilities for working with file and directory paths. Useful for tasks like joining and normalizing paths.
const path = require('path');
// Joining and normalizing paths
const fullPath = path.join(__dirname, 'files', 'example.txt');
const normalizedPath = path.normalize(fullPath);
console.log('Full path:', fullPath);
console.log('Normalized path:', normalizedPath);
os (Operating System)
Provides information about the operating system, such as platform, architecture, and endianness.
const os = require('os');
// Getting information about the operating system
console.log('Platform:', os.platform());
console.log('Architecture:', os.arch());
console.log('Total Memory (bytes):', os.totalmem());
console.log('Free Memory (bytes):', os.freemem());
events
Implements an event emitter pattern, allowing objects to emit and listen for events. It forms the basis for Node.js’s event-driven architecture.
const EventEmitter = require('events');
// Creating a custom event emitter
class MyEmitter extends EventEmitter {}
const myEmitter = new MyEmitter();
// Listening for an event
myEmitter.on('customEvent', (arg) => {
console.log('Event occurred with argument:', arg);
});
// Emitting the event
myEmitter.emit('customEvent', 'Hello, EventEmitter!');
util
Contains utility functions that are commonly used in Node.js applications.
const util = require('util');
// Using the promisify utility to convert a callback-based function to a Promise
const fs = require('fs');
const readFileAsync = util.promisify(fs.readFile);
// Reading a file using a Promise
readFileAsync('example.txt', 'utf8')
.then(data => console.log('File content:', data))
.catch(err => console.error('Error reading file:', err));
crypto
Offers cryptographic functionalities, including hashing, encryption, and decryption.
const crypto = require('crypto');
// Hashing a string using the SHA-256 algorithm
const hash = crypto.createHash('sha256');
hash.update('Hello, Node.js!');
const hashedString = hash.digest('hex');
console.log('Hashed String:', hashedString);
querystring
Provides methods for working with URL query strings.
const querystring = require('querystring');
// Parsing and formatting query strings
const queryString = 'name=John&age=30&city=NewYork';
const parsedObject = querystring.parse(queryString);
const formattedString = querystring.stringify(parsedObject);
console.log('Parsed Object:', parsedObject);
console.log('Formatted String:', formattedString);
url
Allows parsing and formatting of URLs.
const url = require('url');
// Parsing a URL
const urlString = 'https://www.example.com/path?query=example';
const parsedUrl = url.parse(urlString, true);
console.log('Parsed URL:', parsedUrl);
zlib
Provides compression and decompression functionalities using the zlib library.
const zlib = require('zlib');
const fs = require('fs');
// Compressing a file using gzip
const input = fs.createReadStream('example.txt');
const output = fs.createWriteStream('example.txt.gz');
const gzip = zlib.createGzip();
input.pipe(gzip).pipe(output);
Conclusion: Core In-Built Modules of Node.js
In this article, we explored a range of core in-built modules in Node.js, showcasing their fundamental functionalities through practical examples. These modules are integral to Node.js development, offering solutions for tasks ranging from file system operations and HTTP server creation to cryptographic functionalities and compression. The featured modules include:
- File System (
fs
):- Reading and writing files asynchronously.
- HTTP and HTTPS (
http
andhttps
):- Creating simple HTTP and HTTPS servers for handling web requests and responses.
- Path (
path
):- Working with file and directory paths, including joining and normalizing.
- Operating System (
os
):- Retrieving information about the operating system, such as platform and memory details.
- Events (
events
):- Implementing an event emitter pattern for event-driven architecture.
- Utilities (
util
):- Using utility functions, including converting callback-based functions to Promises.
- Cryptography (
crypto
):- Hashing a string using the SHA-256 algorithm.
- Query String (
querystring
):- Parsing and formatting URL query strings.
- URL (
url
):- Parsing URLs for effective manipulation.
- Zlib Compression (
zlib
):- Compressing and decompressing files using the zlib library.