0% found this document useful (0 votes)
43 views72 pages

FSD Unit - 2 - Part-2

Full stack development

Uploaded by

pooja.amanchi
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
43 views72 pages

FSD Unit - 2 - Part-2

Full stack development

Uploaded by

pooja.amanchi
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 72

Course Code: CS712PE

Unit -2 Part-2
Full Stack Development
By B. Lokesh Joel

https://www.softsuave.com/blog/key-trends-in-full-stack-development/
Unit-2: Node.js
• Working with JSON, • Implementing HTTP Clients and Servers in

• Using the Buffer Module to Buffer Data, Using Node.js,

the Stream Module to Stream Data, • Implementing HTTPS Servers and Clients.

• Accessing the File System from Node.js- • Using Additional Node.js Modules-
• Opening, Closing, Writing, Reading Files and • Using the os Module,
other File System Tasks. • Using the util Module,

• Implementing HTTP Services in Node.js- • Using the dns Module,

• Processing URLs, • Using the crypto Module.

• Processing Query Strings and Form Parameters,

• Understanding Request, Response, and Server


Objects,
HTTP and HTTPS Modules in Node.js
▪ Node.js has built-in http and https modules for creating servers
and handling web services.
– These modules provide basic functionality but are low-level and don't
handle routing, cookies, or caching.
– For full-featured web servers, frameworks like Express are preferred
because they simplify these tasks.
Common Use of HTTP Module
▪ The http module is often used to create backend web services
rather than full web servers.
▪ These services allow HTTP servers and clients to communicate
behind a firewall.
▪ Simple HTTP servers using the http module are sufficient for
basic backend communication.
Processing URLs
▪ The URL (Uniform Resource Locator) acts as the address that directs the
HTTP request to the correct server, port, and resource.
▪ Components of a URL include:
– Protocol (e.g., http)
– Hostname (e.g., host.com)
– Port (e.g., 80)
– Pathname (e.g., /resource/path)
– Search query (e.g., ?query=string)
– Hash (e.g., #hash)

▪ The url module in Node.js helps parse and manipulate URL strings into
objects.

http://host:port/path:parameters?query#fragment
Creating a URL Object
▪ The url.parse() method is used to convert a URL string into a URL
object.
url.parse(urlStr, [parseQueryString], [slashesDenoteHost])
– urlStr: The URL string.
– parseQueryString: If true, parses the query string into an object.
– slashesDenoteHost: If true, treats //host/path as a hostname and path.
Resolving URL Components
▪ The url.resolve() method resolves a URL relative to a base URL.
Syntax: url.resolve(from, to)
– from: Original URL.
– to: New relative path or URL part.
Processing Query Strings and Form Parameters
▪ In Node.js, query strings in URLs and form parameters (data sent in the
body of POST requests) are typically simple key-value pairs.
– To work with these values, they need to be parsed into a JavaScript object.
– Node.js provides the querystring module to handle this conversion.

1. Parsing Query Strings


– To convert a query string into a JavaScript object, use the querystring.parse()
method.
– Syntax:
• str: The query string to be parsed (e.g., 'name=Brad&color=red').
• sep: Optional, the separator used between key-value pairs (default is &).
• eq: Optional, the character used to assign values (default is =).
• options: Optional, an object with a maxKeys property to limit the number of keys (default is 1000, set to 0
for no limit).
Processing Query Strings and Form Parameters
2. Converting Objects to Query Strings
– To convert a JavaScript object back into a query string, use the
querystring.stringify() method.
– Syntax:

• obj: The JavaScript object to convert to a query string.


• sep: Optional, the separator (default is &).
• eq: Optional, the assignment character (default is =).
Understanding Request, Response, and Server Objects
▪ When working with the http module in Node.js, understanding
the request and response objects is crucial, as they handle
communication between HTTP clients and servers.
▪ The following section covers key objects:
– ClientRequest,
– ServerResponse,
– IncomingMessage, and
– Server objects.
ClientRequest Object
▪ Purpose: Represents an HTTP request in progress from the client to
the server.
– Created internally when calling http.request() to build an HTTP client.
– It is a Writable stream, so you can use methods like write() to send data and
pipe readable streams into it.

• options: An object that defines details for the request (e.g., hostname, path, method).
• callback: A function called when the server responds, with an IncomingMessage object as a
parameter.
http.ServerResponse Object
▪ The ServerResponse object is created by the Node.js HTTP server
when a request event is received and is passed as the second
argument in the request handler.
– It allows you to formulate and send a response to the client. Since it
implements a Writable stream, it includes functionality for writing data
and sending responses.

▪ Key Features:
– Writable Stream: Can use methods like write() to send data to the client.
– Used in Request Handlers: It's used to handle HTTP responses within the
request handler.
http.ServerResponse Object
▪ Events and Properties of ServerResponse:
– close: Emitted when the connection to the client is closed before the
response.end() finishes.
– headersSent: A Boolean indicating whether headers have been sent
(true) or not (false).
– sendDate: A Boolean that, when set to true, automatically sends the Date
header with the response.
– statusCode: Allows setting the status code (e.g., 200, 404, 500) without
needing to write headers explicitly.
http.IncomingMessage Object
▪ The IncomingMessage
object represents incoming
requests on the server and
responses from the client.
– It can act as both a Readable
stream, allowing data to be
read in chunks, and as a source
of request/response metadata.
http.Server Object
▪ The Server object in Node.js is
the foundation for
implementing an HTTP
server.
– It handles incoming
connections, accepts requests,
and sends responses.
Starting an HTTP Server:
▪ To create and start a server, you use the following methods:
1. http.createServer([requestListener]):
• This method creates a new server object. The optional requestListener is
the callback executed for each incoming request.
Starting an HTTP Server:
2. listen(port, [hostname], [backlog], [callback]):
– Binds the server to a specific port and optional hostname.
• Parameters:
• port: The port number (e.g., 8080).
• hostname: Optional, the server’s IP address (defaults to all available addresses).
• backlog: The maximum number of pending connections.
• callback: Function executed once the server starts listening.

3. close([callback]): Stops the server from accepting new


connections.
Implementing HTTP Clients and Servers
▪ 1. Serving Static Files
▪ 2. Implementing Dynamic GET Servers
▪ 3. Implementing POST Servers
▪ 4. Interacting with External Sources
1. Serving Static Files
▪ The most basic type of server serves static files. The process
involves:
– Starting an HTTP server.
– Using the fs module to read the file from the local system.
– Sending the file content to the client as a response.
static_server.js
index.html

• Run the server: node static_server.js.


• Open your browser and go to http://localhost:3000/ to see the HTML page.
Client Requesting a Static File
Implementing Dynamic GET Servers
▪ Dynamic GET servers in Node.js are used to serve content that can
change based on user input or other factors.
– This could include dynamic HTML files, JSON data, or any other data type.
• Save the above code in a file named dynamic_server.js.
• Run the server using the command: node dynamic_server.js.
• Open your browser and go to http://localhost:8080/.
dynamic_client.js
Implementing POST Servers
▪ POST services allow clients to send data to the server, commonly used for form
submissions or updating resources.
▪ Implementing a POST server is similar to a GET server but involves reading the
request body and processing the data received.
▪ Key Concepts:
– Request Handler: Code that handles incoming requests, specifically for reading and
processing POST data.
– Processing Data: Once the server receives the POST data, it can manipulate or utilize it and
then send a response back to the client.
– Response Finalization: After preparing the response, the server must call end() to finalize and
send it back to the client.
Interacting with External Sources
▪ One of the most common use cases of Node.js HTTP services is to
access external APIs to retrieve or send data.
– This is useful when you need to gather data from third-party services (like
weather, currency exchange rates, or social media feeds) to provide richer
features for users.
– Example: Retrieving Weather Data from an External API
• This example shows how to create a Node.js web service that connects to the
OpenWeatherMap API to retrieve weather information for a specified city.
Interacting with External Sources
▪ Key Concepts:

▪ Handling both GET and POST requests:


– The web service responds to a GET request by returning an HTML form where the user can enter a
city name.
– On a POST request, the server reads the city name from the form, queries the external weather API,
and displays the weather data.

▪ Client-Side Interaction:
– The server also acts as a client when it sends a request to the OpenWeatherMap API to retrieve the
weather information based on the city name provided by the user.

▪ Querying an External API:


– The getWeather() function constructs an HTTP request to the OpenWeatherMap API using the city
name and an API key, then retrieves and processes the response.
Implementing HTTPS Servers and Clients
▪ HTTPS (Hypertext Transfer Protocol Secure) ensures secure
communication between clients and servers. It combines HTTP with
the SSL/TLS protocol to:
1. Encrypt data exchanged between the client and server.
2. Authenticate the server, ensuring the client connects to the intended web
server, preventing man-in-the-middle attacks.

▪ Key Concepts:
– Encryption: HTTPS uses a combination of long-term public/private keys and
short-term session keys to encrypt data.
– Authentication: HTTPS verifies the identity of the server using SSL/TLS
certificates to prevent attacks.
Implementing HTTPS Servers and Clients
▪ Steps for Implementing HTTPS:
▪ Generate Private Key and Certificate:
– Use OpenSSL to generate a private key and a certificate for encryption.
– Generate a private key:
openssl genrsa -out server.pem 2048
– Create a certificate signing request (CSR):
openssl req -new -key server.pem -out server.csr
– Create a self-signed certificate for testing purposes:
openssl x509 -req -days 365 -in server.csr -signkey server.pem -out server.crt
– For production, use a third-party Certificate Authority (CA) to sign the certificate.
Creating an HTTPS Client
▪ Creating an HTTPS client in Node.js is similar to creating an HTTP
client, with the key difference being the need for additional security-
related options, such as specifying SSL/TLS certificates and keys.
– This allows the client to securely communicate with an HTTPS server by
encrypting the data exchanged.

▪ Key Security Options:


– key: The private key used for SSL, typically stored in a .pem file.
– cert: The public x509 certificate used for SSL, also stored in a .pem file.
– agent: The global HTTP agent is disabled (set to false) because the default agent
doesn't support the required options for HTTPS. You can create a custom agent if
needed.
https_client.js
Creating an HTTPS Server
▪ Creating an HTTPS server is nearly identical to creating an
HTTP server, except that you need to specify security options
like the private key (key) and certificate (cert).
https_server.js
Unit-2: Node.js
• Working with JSON, • Implementing HTTP Clients and Servers in

• Using the Buffer Module to Buffer Data, Using Node.js,

the Stream Module to Stream Data, • Implementing HTTPS Servers and Clients.

• Accessing the File System from Node.js- • Using Additional Node.js Modules-
• Opening, Closing, Writing, Reading Files and • Using the os Module,
other File System Tasks. • Using the util Module,

• Implementing HTTP Services in Node.js- • Using the dns Module,

• Processing URLs, • Using the crypto Module.

• Processing Query Strings and Form Parameters,

• Understanding Request, Response, and Server


Objects,
os Module in Node.js
▪ The os module in Node.js provides methods to interact with the
operating system, allowing developers to gather various types of
system-related information.
– This can be useful when building cross-platform applications, system
monitoring tools, or when you need to adapt your app's behavior based on
the underlying OS.
util Module
▪ The util module in Node.js offers utility functions for formatting
strings, checking object types, converting objects to strings, and
facilitating object inheritance.
– It simplifies tasks related to debugging and writing more readable and
maintainable code.
util Module
▪ Features of the util Module
– String Formatting (util.format())
– Checking Object Types
– Converting JavaScript Objects to Strings (util.inspect())
– Customizing Object Inspection
– Inheritance with util.inherits()
util Module
▪ Features of the util Module
– String Formatting (util.format())
• Purpose: Formats strings by accepting a formatter string and a series of arguments.
• Syntax:
util.format(format, [...args])
• Placeholders:
• %s: Replaces with a string.
• %d: Replaces with a number (integer or float).
• %i: Replaces with an integer.
• %f: Replaces with a floating-point value.
• %j: Replaces with a JSON object.
• %: If left empty, is ignored.
util.format('%s = %s', 'Item1', 'Value1'); // Outputs: 'Item1 = Value1'
util.format('%d + %d = %d', 2, 3, 5); // Outputs: '2 + 3 = 5'
util Module
▪ Features of the util Module
– Checking Object Types
• Purpose: To check if an object is of a specific type.
• Example:
console.log([1, 2, 3] instanceof Array); // true
util Module
▪ Features of the util Module
– Converting JavaScript Objects to Strings (util.inspect())
• Purpose: Converts JavaScript objects into string representations, often used for debugging purposes.
• Syntax:
util.inspect(object, [options])
• Options:
• showHidden: Show non-enumerable properties. Default is false.
• depth: Sets how many levels deep the inspection will go. Default is 2. Use null for infinite
recursion.
• colors: Add ANSI color codes to the output. Default is false.
• customInspect: Disable custom inspect() methods defined on the object. Default is true.
• Example:
var obj = { first: 'John', last: 'Doe' };
console.log(util.inspect(obj)); // Outputs: { first: 'John', last: 'Doe' }
util Module
▪ Features of the util Module
– Customizing Object Inspection
• Purpose: Allows you to define custom inspect() methods to control how an object is
represented as a string.
• Example:
var obj = { first: 'John', last: 'Doe' };
obj.inspect = function() {
return `{ name: "${this.first} ${this.last}" }`;
};
console.log(util.inspect(obj)); // Outputs: { name: "John Doe" }
util Module
▪ Features of the util Module
– Inheritance with util.inherits()
• Purpose: Allows one object to inherit the prototype methods of another object,
facilitating inheritance in Node.js.
• Syntax:
util.inherits(constructor, superConstructor)
dns module
▪ The dns module in Node.js provides functions to interact with the
Domain Name System (DNS),
– allowing your application to resolve domain names, perform reverse lookups,
and access various types of DNS records (e.g., A, MX, TXT).
– This is useful for network-based applications, servers, and services that need to
resolve domain names to IP addresses and vice versa.
dns module
▪ Key Methods of the dns Module:
– dns.lookup()
– dns.resolve()
– Specific dns.resolve Methods
– dns.reverse()
dns module
▪ Key Methods of the dns Module:
– dns.lookup()
• Purpose: Resolves a domain name into an IP address.
• Syntax:
dns.lookup(domain, [family], callback);
• Parameters:
• domain: The domain name to resolve.
• family: Optional. Set to 4 for IPv4, 6 for IPv6, or null to resolve both (default: null).
• callback: Receives two arguments: an error and an addresses array.
• Example:
dns.lookup('example.com', (error, addresses) => {
console.log('Addresses:', addresses);
});
Supported Record Types:
A: IPv4 addresses (default).
dns module AAAA: IPv6 addresses.
MX: Mail exchange records.

▪ Key Methods of the dns Module:


TXT: Text records.
SRV: Service records.
PTR: Reverse IP lookups.
– dns.resolve() NS: Name server records.
CNAME: Canonical name records.
• Purpose: Resolves a domain into an array of
specified DNS record types (e.g., A, AAAA, MX,
TXT, etc.). Example:
• Syntax: dns.resolve('example.com', 'MX', (error, addresses)
=> {
dns.resolve(domain, [rrtype], callback);
console.log('MX records:', addresses);
• Parameters: });
• domain: The domain name to resolve.
• rrtype: Optional. Record type to query. Defaults
to 'A' (IPv4 addresses).
• callback: Receives error and addresses array.
Example
dns.resolve4('example.com', (error, addresses) => {
console.log('IPv4 addresses:', addresses);
dns module });

▪ Key Methods of the dns Module:


– Specific dns.resolve Methods
• These methods are more specific versions of dns.resolve() for different record types:
• dns.resolve4(): Resolves IPv4 (A) records.
• dns.resolve6(): Resolves IPv6 (AAAA) records.
• dns.resolveMx(): Resolves MX (Mail Exchange) records.
• dns.resolveTxt(): Resolves TXT records.
• dns.resolveSrv(): Resolves SRV (Service) records.
• dns.resolveNs(): Resolves NS (Name Server) records.
• dns.resolveCname(): Resolves CNAME (Canonical Name) records.
Example:
dns.reverse('8.8.8.8', (error, domains) => {
dns module console.log('Reverse for 8.8.8.8:', domains);
});
▪ Key Methods of the dns Module:
– dns.reverse()
• Purpose: Performs a reverse DNS lookup, resolving an IP address to its associated domain
name(s).
• Syntax:
dns.reverse(ip, callback);
• Parameters:
• ip: The IP address to reverse lookup.
• callback: Receives error and domains array.
crypto Module
▪ The crypto module in Node.js provides cryptographic
functionality that includes encryption, decryption, hashing, and
signing.
– It enables secure communication by encrypting data such as passwords
or sensitive information, making it useful for web applications, APIs, and
other network-based services that handle private data.
Unit-3
Part-1 By B. Lokesh Joel

72

You might also like