UNIT-II-NODEJS
UNIT-II-NODEJS
In Node.js, working with JSON (JavaScript Object Notation) is quite simple because JSON is
natively supported. Here are a few basic operations you can perform when working with JSON data
in Node.js:
You can use JSON.parse() to convert a JSON string into a JavaScript object.
Node.js provides a built-in module called fs (File System) to read from and write to files. You can
use this to read and write JSON files.
const fs = require('fs');
If you’re using Express.js, you can easily handle JSON data in request and response objects.
In this case, when you send a POST request with JSON data to /user, it will be parsed and logged.
Sometimes, when working with JSON, parsing errors can occur, especially if the JSON data is
malformed. Here's how you can handle such errors:
This will catch and log the error if the JSON is malformed.
USING BUFFER MODULE TO BUFFER DATA
In Node.js, the Buffer module is used to handle raw binary data directly. Buffers are especially
useful when working with binary streams, files, or any other kind of raw data that doesn’t naturally
fit into JavaScript's typical string encoding.
1. Creating Buffers
You can create a buffer in a few ways, such as from a string, an array, or allocating a new buffer
with a specific size.
In this example, the string 'Hello, world!' is converted to a buffer using the UTF-8 encoding.
This creates a buffer from an array of numbers, where each number represents a byte in the buffer.
You can access the individual bytes of a buffer using its indices, just like an array.
Example:
const buffer = Buffer.from('Hello, world!');
console.log(buffer[0]); // 72 (ASCII code for 'H')
console.log(buffer[1]); // 101 (ASCII code for 'e')
3. Writing Data to a Buffer
You can modify data inside the buffer, as buffers are mutable.
Buffers can be sliced into smaller buffers without copying the data.
Example:
5. Concatenating Buffers
You can concatenate multiple buffers into a single buffer using Buffer.concat().
Example:
6. Buffer Methods
Example of copy():
Buffers are commonly used in scenarios involving file I/O, streams, or binary protocols. For
example, when reading files in binary mode, fs.readFile() returns a buffer.
const fs = require('fs');
The stream module in Node.js provides a powerful and flexible way to handle streaming data.
Streams allow you to process data piece-by-piece, which is particularly useful when working with
large amounts of data that may not fit into memory all at once, such as reading and writing files or
handling HTTP requests and responses.
1. Readable Streams: Streams that you can read from. Example: fs.createReadStream(),
HTTP requests.
2. Writable Streams: Streams that you can write to. Example: fs.createWriteStream(), HTTP
responses.
3. Duplex Streams: Streams that are both readable and writable. Example: a network socket.
4. Transform Streams: A special type of duplex stream that can modify the data as it is being
read or written. Example: zlib.createGzip() for compression.
Readable streams allow you to read data in chunks, which can be processed as the data is received
(avoiding the need to load the entire file into memory).
const fs = require('fs');
// Handle errors
readableStream.on('error', (err) => {
console.error('Error reading stream:', err);
});
Writable streams allow you to write data to a destination. Example: writing to a file, sending HTTP
responses.
One of the most common use cases for streams is piping data from one stream to another. You can
use the .pipe() method to send data from a readable stream to a writable stream. This is particularly
useful for tasks like file copying, or reading from a network socket and sending the data to a file.
const fs = require('fs');
writableStream.on('finish', () => {
console.log('File has been copied!');
});
4. Transform Streams
A transform stream is a type of duplex stream where data is transformed as it is read and written.
For example, you could use it to compress data, convert it to a different format, or filter content.
const fs = require('fs');
const zlib = require('zlib');
writableStream.on('finish', () => {
console.log('File has been compressed!');
});
Streams are often used in web servers, especially when handling large HTTP requests and
responses.
app.listen(3000, () => {
console.log('Server is running on port 3000');
});
Streams in Node.js also support flow control, meaning you can control when data is read from a
stream. The default behavior is flowing mode, where data is read automatically as it becomes
available.
You can switch to paused mode if you want to control when data is read.
const fs = require('fs');
// Create a readable stream in paused mode
const readableStream = fs.createReadStream('example.txt', { highWaterMark: 16 });
7. Error Handling
Proper error handling is crucial when working with streams. You should listen for the 'error' event
on both readable and writable streams.
const fs = require('fs');
Streams are powerful for handling large or continuous data and are a fundamental part of Node.js
for I/O-bound tasks.
Node.js provides a built-in fs (file system) module that allows you to perform various tasks related
to files and directories, such as opening, closing, reading, writing, and manipulating files. The fs
module offers both synchronous and asynchronous methods to handle these tasks, which makes it
highly flexible for different use cases.
To interact with the file system, you first need to require the fs module:
const fs = require('fs');
2. Opening a File
The fs.open() method opens a file asynchronously, providing you with a file descriptor that you can
use for reading or writing.
Const fs=require(‘fs’);
fs.open('example.txt', 'r', (err, fd) => {
if (err) {
console.error('Error opening file:', err);
return;
}
console.log('File opened successfully with file descriptor:', fd);
});
If you prefer to use the synchronous version, you can use fs.openSync():
Const fs=require(‘fs’);
try {
const fd = fs.openSync('example.txt', 'r');
console.log('File opened successfully with file descriptor:', fd);
} catch (err) {
console.error('Error opening file:', err);
}
3. Closing a File
You can close an opened file using fs.close(), providing the file descriptor that you got from
fs.open().
Const fs=require(‘fs’);
fs.open('example.txt', 'r', (err, fd) => {
if (err) {
console.error('Error opening file:', err);
return;
}
Const fs=require(‘fs’);
try {
const fd = fs.openSync('example.txt', 'r');
fs.closeSync(fd);
console.log('File closed successfully');
} catch (err) {
console.error('Error closing file:', err);
}
4. Reading a File
The fs.read() method reads data from an opened file. You must first open the file using fs.open(),
and then you can read from it.
try {
const data = fs.readFileSync('example.txt', 'utf8');
console.log('File content:', data);
} catch (err) {
console.error('Error reading file:', err);
}
5. Writing to a File
The fs.write() method allows you to write data to a file. You must open the file first.
try {
fs.writeFileSync('example.txt', 'Hello, world!');
console.log('Data written to file');
} catch (err) {
console.error('Error writing to file:', err);
}
7. Renaming a File
8. Deleting a File
if (fs.existsSync('example.txt')) {
console.log('File exists');
} else {
console.log('File does not exist');
}
Summary
The fs module provides both asynchronous and synchronous methods for performing file system
operations. It is highly versatile, allowing you to:
For most I/O tasks, the asynchronous methods are preferred, as they avoid blocking the event loop,
making your application more efficient and responsive.
This basic server sends a "Hello, World!" message when you visit http://localhost:3000/ in your
browser.
When a client makes an HTTP request, it includes a URL that contains important information such
as the path, query parameters, and sometimes fragments. In Node.js, we can process these
components and use them to perform different actions.
To handle URLs and extract query parameters, we can use the url module, which provides utility
methods to parse and format URLs.
Example request:
Visit http://localhost:3000/products?category=electronics&price=1000
Path: /products
Query Parameters: { category: 'electronics', price: '1000' }
{
"message": "Request received",
"path": "/products",
"query": {
"category": "electronics",
"price": "1000"
}
}
The req (request) object contains the HTTP method (GET, POST, PUT, DELETE, etc.) that was
used in the request. We can check the HTTP method and route the request accordingly.
Example requests:
You can use dynamic route matching by processing parts of the URL path. You can extract
variables from the path using regular expressions or by splitting the URL path.
Example request:
Visit http://localhost:3000/user/12345
{
"message": "User details for user ID 12345",
"userId": "12345"
}
You can combine both dynamic path parameters and query parameters to create more sophisticated
URLs.
res.statusCode = 200;
res.setHeader('Content-Type', 'application/json');
res.end(JSON.stringify({
message: `Displaying products in category ${category} with price ${price}`,
category: category,
price: price,
}));
} else {
res.statusCode = 404;
res.end('Not Found');
}
});
Example request:
Visit http://localhost:3000/products?category=electronics&price=1000
{
"message": "Displaying products in category electronics with price 1000",
"category": "electronics",
"price": "1000"
}
To handle requests for routes that are not defined, you can implement a default route that returns a
404 response.
Conclusion
In Node.js, handling HTTP requests and processing URLs is a core part of building HTTP services.
Using the built-in http and url modules, you can:
These techniques enable you to build flexible and efficient web services and APIs in Node.js.
In Node.js, processing query strings (from URLs) and form parameters (from POST requests) is a
common task, especially when building web applications or APIs. We can handle both of these
types of data with the help of built-in modules like url, querystring, and handling request bodies
directly.
Let’s dive into how we can process query strings (GET requests) and form parameters (POST
requests) in Node.js.
Query strings are the part of the URL that comes after the ? character and are used to send data to
the server. They are typically used in GET requests.
Example URL:
http://localhost:3000/search?category=electronics&price=1000
category=electronics
price=1000
These are query parameters that we can extract from the request.
Node.js provides the url module to parse the request URL and extract query parameters.
Example Request:
URL: http://localhost:3000/search?category=electronics&price=1000
Response:
{
"message": "Search results",
"category": "electronics",
"price": "1000"
}
In the example above, the code checks if the query parameters are provided. If they are missing, it
uses default values ('all' for category and 'any' for price).
Form parameters are typically sent in POST requests, and they contain data submitted from forms
(e.g., login forms, registration forms). When dealing with form parameters, the data is usually sent
in the request body.
Node.js does not parse the body of a POST request by default. To process form parameters, you
need to read the body and parse it.
You can use the querystring module (or URLSearchParams in newer Node.js versions) to parse
form data, but we’ll first need to collect the data from the request body.
URL: http://localhost:3000/submit
Form Data (submitted via a form):
o username=alice
o password=secret123
To simulate sending a POST request from a form, you can use curl or an HTML form.
Example with curl:
Response:
{
"message": "Form submitted successfully",
"username": "alice",
"password": "secret123"
}
In modern web applications, it's common to send JSON data in POST requests, especially when
interacting with APIs. To handle JSON payloads, you need to parse the request body as JSON.
Response:
{
"message": "JSON data received",
"name": "John",
"age": 30
}
Sometimes, form data or query parameters can contain special characters that need to be encoded or
decoded properly. This can be done using encodeURIComponent and decodeURIComponent.
You can use these functions when constructing or processing URLs to handle special characters
properly.
Conclusion
In Node.js, you can process query strings (GET request parameters) and form parameters (POST
request body) using built-in modules like url, querystring, and http. Here are the main techniques
we covered:
Query Strings (GET Requests): Extracting data from the URL using url.parse().
Form Parameters (POST Requests): Parsing form data from the request body using
querystring.parse() for URL-encoded data.
JSON Data (POST Requests): Handling JSON payloads by parsing the body as JSON with
JSON.parse().
URL Encoding/Decoding: Using encodeURIComponent and decodeURIComponent to
handle special characters.
These are common tasks when building web services and APIs in Node.js, and these approaches
can be easily extended to handle more complex use cases.
In Node.js, the http module provides the core functionality to create HTTP servers and process
HTTP requests and responses. The http module's server is built around the request (req) and
response (res) objects, which play crucial roles in handling incoming requests and sending out
responses.
The request object represents the incoming HTTP request made by a client (e.g., a browser, mobile
app, or any HTTP client). It contains important information about the request such as headers, URL,
HTTP method (GET, POST, etc.), query parameters, request body, and more.
req.method: The HTTP method used for the request (e.g., 'GET', 'POST', 'PUT',
'DELETE').
req.url: The full URL of the request, including the path and query string (e.g., /home?
search=query).
req.headers: An object containing the request headers, such as User-Agent, Content-Type,
Authorization, etc.
req.body: This contains the body of the request, which is typically populated in POST and
PUT requests. It requires parsing (e.g., JSON or URL-encoded data).
req.query: Contains the query string parameters from the URL (e.g., ?
name=John&age=30). For parsing query strings, url.parse() can be used or express
framework can parse it automatically.
req.params: In routes with dynamic path parameters, the req.params object stores those
variables. For example, in a route like /user/:id, req.params.id will contain the value of id.
res.statusCode = 200;
res.setHeader('Content-Type', 'text/plain');
res.end('Request details logged.');
});
server.listen(3000, () => {
console.log('Server is running at http://localhost:3000/');
});
The response object represents the HTTP response that the server sends back to the client. It
contains methods and properties for setting the status code, headers, and body of the response.
res.statusCode: Set the HTTP status code for the response (e.g., 200 for success, 404 for
not found).
res.setHeader(name, value): Set a specific HTTP header in the response. For example, you
can use res.setHeader('Content-Type', 'application/json') to set the response type to JSON.
res.end([data]): End the response and optionally send data (e.g., a string or a buffer). If no
data is provided, the response is ended with no body.
res.write(data): Used to send data in chunks (e.g., for streaming large files). You can call
res.write() multiple times, and finally call res.end() to finish the response.
res.json(obj) (in frameworks like Express): Sends a JSON response to the client. This is not
available in the core http module but can be implemented by calling
res.end(JSON.stringify(obj)).
server.listen(3000, () => {
console.log('Server is running at http://localhost:3000/');
});
3. The server Object
The server object represents the HTTP server itself. It's an instance of the http.Server class, which is
created using http.createServer().
The server.listen() method binds the server to a specific port and makes it listen for incoming
requests.
server.listen(port, hostname, callback): This method listens on the specified port (e.g.,
3000) and hostname (optional, usually 'localhost'). The callback function is executed once
the server starts.
server.close(): This method is used to stop the server from accepting new connections.
server.listen(3000, () => {
console.log('Server is running at http://localhost:3000/');
});
1. Server receives the request: The server created with http.createServer() listens for
incoming requests. When a request comes in, the callback function you provided is invoked,
and the req (request) and res (response) objects are passed to it.
2. Request processing: Inside the callback function, you inspect the req object to process the
request, including the HTTP method, headers, URL, and body. You can also access
parameters from the query string or URL path (e.g., req.query, req.params).
3. Response generation: After processing the request, you use the res object to build the
response. You can set status codes (e.g., res.statusCode = 200), set headers (e.g.,
res.setHeader('Content-Type', 'application/json')), and send the response body (e.g.,
res.end('Hello, World!')).
4. Server sends the response: Once the response is fully constructed, the res.end() method
sends the response back to the client.
res.statusCode = 200;
res.setHeader('Content-Type', 'text/plain');
res.end(`Hello, ${name}!`); // Respond with a greeting message
} else {
res.statusCode = 404;
res.setHeader('Content-Type', 'text/plain');
res.end('Not Found'); // Handle unknown routes
}
});
server.listen(3000, () => {
console.log('Server running at http://localhost:3000/');
});
Example Request:
URL: http://localhost:3000/greet?name=John
Response:
Hello, John!
req (Request Object): Represents the incoming HTTP request. It contains details about the
request, such as the URL, HTTP method, headers, query parameters, and body data.
res (Response Object): Represents the outgoing HTTP response. You use it to set the status
code, headers, and body of the response.
server (Server Object): Represents the HTTP server that listens for incoming requests and
manages responses. It's created using http.createServer() and listens on a specified port.
Together, these objects form the core functionality for handling HTTP requests and responses in
Node.js.
In Node.js, you can implement both HTTP servers (to handle incoming requests) and HTTP
clients (to make requests to other servers). Node.js provides built-in modules such as http and https
to implement both.
An HTTP server listens for incoming HTTP requests from clients and sends responses. The http
module allows you to create a simple server by using the http.createServer() method.
Here is a basic example of creating an HTTP server that responds with "Hello, World!" for every
request.
Explanation:
An HTTP client in Node.js makes requests to other servers (e.g., sending a GET request to an API
or making a POST request). You can use the http module or the https module, depending on
whether you're connecting to a secure or non-secure server.
Explanation:
http.request(options, callback): Makes an HTTP request to the server. The options object
specifies the hostname, path, and method (GET in this case).
res.on('data', callback): Listens for chunks of data that the server sends back in response.
res.on('end', callback): Fires when the entire response is received.
req.end(): Sends the request to the server.
You can also use the HTTP client to send data using the POST method.
Explanation:
method: 'POST': The HTTP method used to send data to the server.
headers: The Content-Type header tells the server that the body of the request contains
JSON data. The Content-Length header tells the server the length of the data being sent.
req.write(postData): Writes the data to be sent in the body of the request.
req.end(): Ends the request, sending the data.
When making requests with the HTTP client, it is important to handle errors. Errors can occur due
to network issues, timeouts, or server unavailability.
res.on('end', () => {
console.log('Response:', data);
});
});
req.end();
If you are making requests to a secure server (e.g., https:// URLs), you should use the https module
instead of the http module. The usage is the same, but it works for HTTPS connections.
res.on('end', () => {
console.log('Response:', data);
});
});
req.on('error', (err) => {
console.error('Error:', err.message);
});
req.end();
For more advanced HTTP client functionality (e.g., handling cookies, retries, redirects), you might
want to use external libraries like axios, node-fetch, or request (deprecated).
axios.get('https://jsonplaceholder.typicode.com/todos/1')
.then(response => {
console.log('Response:', response.data); // Log the response data
})
.catch(error => {
console.error('Error:', error.message);
});
Conclusion
In Node.js, you can build both HTTP clients and servers using the built-in http and https modules:
HTTP Server: Use http.createServer() to create a server that listens for incoming requests
and sends responses.
HTTP Client: Use http.request() or https.request() to send requests to other servers and
handle their responses.
POST Requests: Send data in the body of the request using req.write() for POST, PUT, or
PATCH methods.
For more advanced scenarios, you may want to explore external libraries like axios, which
simplifies making HTTP requests and handling responses.
In Node.js, you can implement both HTTPS servers (to handle secure incoming requests) and
HTTPS clients (to make secure requests to other servers). This is accomplished using the https
module, which provides the ability to create secure servers and clients that use SSL/TLS encryption.
To implement an HTTPS server in Node.js, you need an SSL/TLS certificate. These certificates are
used to encrypt the communication between the server and the client.
Prerequisites:
1. An SSL certificate (.crt) and a private key (.key). You can generate these using tools like
openssl, or use a service to obtain one.
2. These files will be used to configure the HTTPS server.
Explanation:
SSL/TLS Certificates: The key, cert, and optionally ca are used to configure the HTTPS
server. These files contain the server’s private key, certificate, and optionally the CA
certificate, respectively.
o key: The server's private key.
An HTTPS client can be used to make secure requests to remote HTTPS servers. The https module
in Node.js is used to make these requests.
Explanation:
In some cases, you might need to configure the HTTPS client to accept certain SSL/TLS certificates
(e.g., when dealing with self-signed certificates). You can pass SSL options in the https.request()
function.
res.on('end', () => {
console.log('Response:', data); // Log the response body
});
});
Explanation:
4. Self-Signed Certificates
If you are using self-signed certificates for local development or testing, you may need to add an
additional option to the client (rejectUnauthorized: false) to allow the connection, as self-signed
certificates are not trusted by default.
res.on('end', () => {
console.log('Response:', data);
});
});
req.end();
If you want to test an HTTPS server locally with a self-signed certificate, you can generate one
using OpenSSL and then configure your HTTPS server accordingly.
To create a self-signed certificate for local testing, you can run the following OpenSSL command:
openssl req -x509 -newkey rsa:4096 -keyout private-key.key -out certificate.crt -days 365
Conclusion
HTTPS Server: Use the https module with an SSL/TLS certificate and private key to create
a secure server.
HTTPS Client: Use the https module to make secure requests to HTTPS servers, passing
SSL/TLS certificates if needed.
Self-Signed Certificates: If you're using self-signed certificates for local development,
configure both the client and server to allow them (e.g., rejectUnauthorized: false for the
client).
For more advanced use cases, you can also explore features like mutual TLS (client-side
authentication) and configure additional SSL options to enhance security.
The os module in Node.js provides a number of operating system-related utility methods that can be
helpful in retrieving information about the system, including CPU, memory, and network-related
data. It's a built-in module, so you don’t need to install anything extra to use it.
Here are some of the commonly used methods in the os module and how you can use them:
1.1. os.platform()
This method returns a string identifying the operating system platform. For example, it could return
'darwin' for macOS, 'linux' for Linux, or 'win32' for Windows.
const os = require('os');
console.log('Platform:', os.platform());
1.2. os.arch()
This method returns a string identifying the architecture of the operating system. It could return
'x64', 'arm', 'ia32', etc.
console.log('Architecture:', os.arch());
1.3. os.hostname()
console.log('Hostname:', os.hostname());
1.4. os.type()
This method returns a string identifying the operating system name (e.g., 'Linux', 'Darwin', or
'Windows_NT').
1.5. os.release()
1.6. os.uptime()
Returns the system uptime in seconds (how long the system has been running).
2.1. os.totalmem()
2.2. os.freemem()
2.3. os.cpus()
Returns an array of objects containing information about each logical CPU core. Each object
contains details like model, speed, and times spent in user, system, and idle modes.
3.1. os.networkInterfaces()
Returns an object containing network interfaces that are available on the system. This is useful for
retrieving IP addresses and other network-related data.
{
"eth0": [
{
"address": "192.168.1.10",
"netmask": "255.255.255.0",
"family": "IPv4",
"mac": "00:1a:2b:3c:4d:5e",
"internal": false,
"cidr": "192.168.1.10/24"
}
],
"lo0": [
{
"address": "127.0.0.1",
"netmask": "255.0.0.0",
"family": "IPv4",
"mac": "00:00:00:00:00:00",
"internal": true,
"cidr": "127.0.0.1/8"
}
]
}
4.1. os.userInfo()
This method returns an object with the current user's information (e.g., username, home directory,
shell).
Example output:
{
"username": "your-username",
"uid": 501,
"gid": 20,
"shell": "/bin/bash",
"homedir": "/Users/your-username"
}
5.1. os.tmpdir()
6.1. os.endianness()
Returns the endianness of the system’s CPU. It can return 'BE' for big-endian or 'LE' for little-
endian.
console.log('Endianness:', os.endianness());
7.1. os.loadavg()
Returns an array with three load averages for the last 1, 5, and 15 minutes. This is usually a measure
of the system's load and how many processes are in the queue for CPU.
Example output:
8.1. os.constants
This provides system constants such as signals, file system flags, and error codes.
Example usage:
Here’s an example that combines some of the above methods to print a summary of system
information:
const os = require('os');
console.log('Platform:', os.platform());
console.log('Architecture:', os.arch());
console.log('Hostname:', os.hostname());
console.log('OS Type:', os.type());
console.log('OS Release:', os.release());
console.log('Uptime:', os.uptime(), 'seconds');
console.log('Total Memory:', os.totalmem(), 'bytes');
console.log('Free Memory:', os.freemem(), 'bytes');
console.log('CPUs:', os.cpus());
console.log('Network Interfaces:', os.networkInterfaces());
console.log('User Info:', os.userInfo());
console.log('Temporary Directory:', os.tmpdir());
console.log('Endianness:', os.endianness());
console.log('Load Average:', os.loadavg());
Conclusion
The os module is a valuable tool in Node.js for interacting with and retrieving system-related
information. It's commonly used when you need to gather data on the environment your application
is running on, such as CPU details, memory usage, and networking information.
The util module in Node.js provides a set of utility functions that help in working with objects,
functions, and other built-in JavaScript types. It can be quite useful for tasks such as inspecting
objects, formatting strings, and using inheritance, among other things.
1. util.format()
The util.format() function is similar to printf in other languages like C. It allows you to format
strings with placeholders, which are then replaced by the provided arguments.
Example:
You can use multiple placeholders, like %s for strings, %d for integers, %j for JSON, and more.
2. util.inspect()
Example:
const obj = {
name: 'John',
age: 25,
hobbies: ['reading', 'coding'],
};
3. util.promisify()
The util.promisify() function converts callback-based functions into ones that return a Promise. This
is especially helpful when you want to use async/await syntax with legacy callback-based APIs.
Example:
const fs = require('fs');
const util = require('util');
readFile();
This makes fs.readFile() return a promise instead of using a callback, allowing you to use
async/await with it.
4. util.callbackify()
util.callbackify() is the opposite of promisify(). It converts a function that returns a Promise into a
function that uses a callback. This can be useful when you're working with APIs that expect
callback-based functions.
Example:
5. util.inherits()
The util.inherits() function is used for setting up inheritance in Node.js. It allows one constructor
function to inherit from another.
Example:
Animal.prototype.speak = function() {
console.log(`${this.name} makes a sound`);
};
// Set up inheritance
util.inherits(Dog, Animal);
Here, Dog inherits from Animal. The Dog class can now access methods from Animal.
6. util.deprecate()
The util.deprecate() function allows you to mark a function as deprecated, and it will show a
warning when the function is called.
Example:
// A deprecated function
function oldFunction() {
console.log('This function is deprecated');
}
This will print a warning when the function is called, alerting the developer that the function is
deprecated.
7. util.isArray()
This method checks if the given value is an array. It returns true if the value is an array, otherwise
false.
8. util.isError()
This method checks if the value is an instance of Error. It returns true if the value is an error,
otherwise false.
// Create an object
const obj = {
name: 'Alice',
age: 30,
greet: function() { return 'Hello, ' + this.name; },
};
// Deprecate a function
const deprecatedFunc = util.deprecate(function() {
console.log('This is deprecated');
}, 'This function is deprecated!');
Conclusion
The util module in Node.js offers a variety of utility functions that simplify working with
asynchronous code, object inspection, formatting, inheritance, and more. It’s a powerful tool for
developers working with Node.js, especially when dealing with legacy callback-based APIs,
debugging, or working with complex data structures.
The dns module in Node.js provides an API for performing DNS (Domain Name System) lookups
and resolving domain names. This module is essential when you need to interact with DNS records,
perform reverse lookups, or resolve hostnames to IP addresses.
Here’s an overview of how you can use the dns module in Node.js:
The dns module provides functions that allow you to resolve domain names into their respective IP
addresses. There are both callback-based and Promise-based versions of these methods.
2.1. dns.lookup()
Example:
Example Output:
Address: 172.217.6.36
Family: 4
address: The resolved IP address.
family: Indicates whether the IP is IPv4 (4) or IPv6 (6).
2.2. dns.promises.lookup()
This is the Promise-based version of dns.lookup(). It returns a promise that resolves with the
address and family.
Example:
resolveHostname();
You can use the dns module to resolve various types of DNS records, such as A records, MX
records, and more.
3.1. dns.resolve()
The dns.resolve() method resolves a domain name into different types of records (like A, AAAA,
MX, etc.).
Example (A records):
Example Output:
3.2. dns.resolveMx()
The resolveMx() method retrieves the mail exchange (MX) records for a domain.
Example:
Example Output:
MX Records: [
{ exchange: 'alt1.gmail-smtp-in.l.google.com', priority: 5 },
{ exchange: 'alt2.gmail-smtp-in.l.google.com', priority: 5 },
{ exchange: 'gmail-smtp-in.l.google.com', priority: 10 },
{ exchange: 'alt3.gmail-smtp-in.l.google.com', priority: 5 },
{ exchange: 'alt4.gmail-smtp-in.l.google.com', priority: 5 }
]
3.3. dns.resolveTxt()
The resolveTxt() method retrieves the TXT records for a domain. TXT records are often used for
various domain-related configurations like SPF (Sender Policy Framework) records.
Example:
Example Output:
You can use the dns.reverse() method to get the hostnames for a given IP address. This is useful
when you want to perform a reverse DNS lookup to find out the domain associated with a given IP.
Example:
Example Output:
Hostnames: [ 'dns.google' ]
5. dns.resolveSrv()
This method resolves a domain name to its SRV (Service) records, which are used to define the
location of servers for specified services.
Example:
Example Output:
SRV Records: [
{ priority: 10, weight: 60, port: 5060, name: 'sipserver.google.com' }
]
6. dns.resolveNs()
The resolveNs() method retrieves the nameserver (NS) records for a domain.
Example:
Example Output:
7. dns.resolveCname()
The resolveCname() method resolves a CNAME (Canonical Name) record, which maps an alias
domain name to the canonical domain name.
Example:
Example Output:
8. dns.lookupService()
The dns.lookupService() method performs a reverse lookup to get the service for a specific IP
address and port.
Example:
Example Output:
Hostname: dns.google
Service: domain
Node.js DNS methods also support promise-based versions for cleaner asynchronous code using
async/await.
resolveMX();
Conclusion
The dns module in Node.js provides a rich set of methods to interact with DNS and perform domain
name resolution, reverse lookups, and retrieve various DNS record types. It supports both callback
and promise-based patterns, making it flexible for handling asynchronous operations.
This module is especially useful when building networked applications, setting up custom DNS
queries, or diagnosing DNS issues.
The crypto module in Node.js provides a set of cryptographic functionalities that allow you to
perform tasks such as hashing, encryption, decryption, HMACs (Hash-based Message
Authentication Codes), and more. It's essential when building secure applications that need to
handle sensitive data.
To use the crypto module in Node.js, you can simply require it like this:
const crypto = require('crypto');
2. Creating Hashes
Hashing is the process of converting data into a fixed-length string, typically used for storing
passwords or verifying data integrity. The crypto module supports several hashing algorithms like
SHA-256, SHA-512, MD5, etc.
HMAC is used to verify both the data integrity and authenticity of a message. It uses a
cryptographic key along with a hash function.
The crypto module can be used to perform symmetric encryption (using the same key for both
encryption and decryption) and asymmetric encryption (using a pair of public and private keys).
AES (Advanced Encryption Standard) is a symmetric encryption algorithm. Both the encryption
and decryption use the same key.
RSA is a type of asymmetric encryption, where a public key is used for encryption, and a private
key is used for decryption.
The crypto module can be used to generate random data for various purposes like generating keys,
salts, or nonces.
You can also use the crypto.randomInt() method to generate a random integer.
PBKDF2 (Password-Based Key Derivation Function 2) is used to securely derive a key from a
password, making it more resistant to attacks like brute-forcing.
The crypto module allows you to sign data using a private key and verify it using a public key,
which is essential for ensuring data authenticity and integrity.
Example: Signing Data
console.log('Signature:', signature);
8. Stream-Based Encryption
For larger data (such as encrypting/decrypting files), you can use streams to perform encryption in
chunks without loading the entire file into memory.
const fs = require('fs');
const crypto = require('crypto');
input.pipe(cipher).pipe(output);
const fs = require('fs');
const crypto = require('crypto');
input.pipe(decipher).pipe(output);
Conclusion
The crypto module in Node.js provides a wide range of cryptographic functions for hashing,
encryption, signing, key derivation, and more. It's essential for building secure applications,
handling sensitive data like passwords, and implementing encryption/decryption mechanisms.