0% found this document useful (0 votes)
37 views98 pages

Fswd-Unit 2

Uploaded by

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

Fswd-Unit 2

Uploaded by

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

UNIT II NODE JS

Basics of Node JS – Installation – Working with Node


packages – Using Node package manager – Creating a
simple Node.js application – Using Events – Listeners
–Timers - Callbacks – Handling Data I/O –
Implementing HTTP services in Node.js
Basics of Node JS
• Node.js was developed in 2009 by Ryan Dahl.
• It is an extremely scalable server-side environment that allows
developers to more easily bridge the gap between client and
server.
• The fact that Node.js is written in JavaScript allows developers
to easily navigate back and forth between client and server
code and even reuse code between the two environments
• The Node.js environment is clean and easy to install,
configure, and deploy.
• Advantages: Scalability , ease of maintenance and faster
development.
What Is Node.js Used For?
• Node.js isn’t a programming language or framework;
instead, it’s an environment for them.
• Its code will handle HTTP traffic, the most common use
is as a webserver.
• Node.js can also be used for a variety of other web
services such as:
– Web services APIs such as REST
– Real-time multiplayer games
– Backend web services such as cross-domain, server-side
requests
– Web-based applications
– Multiclient communication such as IM
The key features of Node.js
• Asynchronous/Non-blocking thread execution – Every
API of the Node.js library is non-blocking. While waiting
for a response for something outside the execution
chain, the next tasks in the stack are continuously
executed.
• Event-driven – A server built with Node.js uses a
notification mechanism called “Events” to receive and
track responses of previous API requests. Event Loop
allows Node.js to execute all the non-blocking
operations.
• Cross-platform compatibility – Node.js is compatible
with various platforms like Windows, Linux, Mac OS X,
Unix, and mobile platforms.
• Node.js – runtime environment for executing
JS outside the client’s browser.
• To run JS outside we need Backend server(i.e
Virtual Machine) like V8 by google.
• Node.js framework types:
– MVC framework
– Full-stack MVC framework
– REST API(Representational state transfer)
1. Requests – Based on the specific tasks users need to
perform in a web application, the requests can either be
blocking (complex) or non-blocking (simple).
2. Nodejs server – It accepts user requests, processes
them, and returns the results to the corresponding users.
3. Event queue – It stores the incoming requests and passes
them sequentially to the Event Pool.
4. Event pool – After receiving the client requests from the
event queue, it sends responses to corresponding clients.
5. Thread pool – It contains the threads available for
performing those operations necessary to process
requests.
6. External resources – The external resources are used for
blocking client requests and can be used for
computation, data storage, and more.
Installing Node.js
• To easily install Node.js, download an installer from the
Node.js website at http://nodejs.org.
• The Node.js installer installs the necessary files on your PC
to get Node.js up and running.
• No additional configuration is necessary to start creating
Node.js applications
1. Looking at the Node.js Install Location
– At the install location, we have a a node_modules folder. the
executables in the Node.js install location that you need to get
started:
– node: This file starts a Node.js JavaScript VM.
– npm: This command is used to manage the Node.js packages
– node_modules: This folder contains the installed Node.js
packages.
2. Verify Node.js Executable
– Open a console prompt and execute the following
command to bring up a Node.js VM:
node
– At the Node.js prompt execute the following to write
"Hello World" to the screen
>console.log("Hello World");
– You should see "Hello World" output to the console
screen.
– Now exit the console using Ctrl+C in Windows or Cmd+C
on a Mac.
– Next, verify that the npm command is working by executing
the following command in the OS console prompt
npm version
• You should see output similar to the following
{ npm: '3.10.5',
ares: '1.10.1-DEV',
http_parser: '2.7.0',
icu: '57.1',
modules: '48',
node: '6.5.0',
openssl: '1.0.2h',
uv: '1.9.1',
v8: '5.1.281.81',
zlib: '1.2.8'}
3. Selecting a Node.js IDE(Integrated Development
Environment)
Node Package Manager
• NPM is a package manager for Node.js packages,
NPM program is installed on your computer when
you install Node.js
• A package in Node.js contains all the files you
need for a module.
• Modules are JavaScript libraries you can include
in your project.
• NPM allows open-source web developers to share
and borrow packages for app development.
• NPM functionalities:
– It provides online repositories for node.js packages/modules.
– It also provides command line utility to install Node.js packages.
• Components of NPM
– Website: Packages can be found from the official NPM website
for the project
– Command Line Interface (CLI): To interface with NPM packages
and repositories, the CLI runs from your computer's terminal.
– Registry: It has a huge database of JavaScript projects and meta-
data
• NPM can install all the dependencies of a project through
the package.json file. It can also update and uninstall
packages.
Commands
• To check npm version
npm-v

• If the installed version is not latest, update it using the given


syntax:
npm update npm@latest-g

• As npm is a global package,


-g flag is used to update it globally.

• To access NPM help, write npmlhelp in the command


prompt or terminal window.
npm help
WORKING WITH PACKAGES
• What Are Node Packaged Modules?
– A Node Packaged Module is a packaged library
that can easily be shared, reused, and installed in
different projects.
– Node Packaged Modules include a package.json
(java script object notation) file that defines the
packages.
– The package. json file includes informational
metadata, such as the name, version author, and
contributors, as well as control metadata
Node Package Registry
• The Node modules have a managed location
called the Node Package Registry where
packages are registered.
• This allows you to publish your own packages
in a location where others can use them as
well as download packages that others have
created.
• The Node Package Registry is located at
https://npmjs.com.
Using the Node Package Manager
• The Node Package Manager you have already
seen is a command-line utility.
• It allows you to find, install, remove, publish,
and do everything else related to Node
Package Modules.
• The Node Package Manager provides the link
between the Node Package Registry and
your development environment.
Lists the Node Package Manager
commands
Searching for Node Package Modules
Type the command in command prompt
npm search <search_string>
Eg: npm search openssl
Installing Node Packaged Modules
npm install
<module_name>
Eg: npm install express
The output of the npm
install command
displays the
dependency hierarchy
installed with the
module.
Using package.json
• All Node modules must include a package.json file in their
root directory.
• The package.json file is a simple JSON text file that defines the
module including dependencies.
• The package. json file can contain a number of different
directives to tell the Node Package Manager how to handle
the module.
• The following is an example of a package.json file with a
name, version, description, and dependencies:
• Create a package.json file: Create a package.json file to
store useful metadata about the project and help to
manage the project's dependent Node.js modules.
• Create a package.json file by
– running a CLI questionnaire or
– creating a default package.json file.
• Running a CLI questionnaire
– To create a package.json file with values that you supply, use
the npm init command.
1. On the command line, navigate to the root directory of your
package.
cd /path/to/package
2. Run the following command:
npm init
3. Answer the questions in the command line questionnaire.
• Basic metadata provided by developers:
– name: Name of the project. The name must be: one word,
Jowercase, not start with an '' or '.‘
– version: current version of the modules. It must follow the
semantic versioning guidelines, c.g., 1.0.0
– description: provides more information about the project
– Engines: It is an object used to specify the library versions
required for the application to run.
– license: the project's license
– Scripts: Scripts are key-value pairs used to perform a
series of tasks such as building, testing, etc.
– Main: Main is the entry point of the application and
should refer to the main page of your app.
– Homepage: Homepage is used to specify the landing page
of the app.
• Creating a default package.json file
– To create a default package.json using information
extracted from the current directory, use the npm
init command with the --yes or -y flag.
1. On the command line, navigate to the root
directory of your package.
cd /path/to/package
2. Run the following command:
npm init –yes
• Installing all dependencies:
– type npm install in the root of the project, and it will automatically
alter the package.json file to include the dependencies.
– Dependencies: It denotes the list of modules and packages required
for the application to function. It is added to the dependency list when
installed.
– dev Dependencies: are modules that are not required to run the
application but are needed in the development phase.
• By-save flag one can control where the packages are to be
installed.
npm install express-save
• -save-prod: Using this packages will appear in Dependencies
which is also by default.
• -save-dev: Using this packages will get appear in
devDependencies and will only be used in the development
mode.
CREATING A SIMPLE NODE.JS APPLICATION
• Creating the simple node.js application in two ways:
1. Console based
2. Web based
1. Creating a simple hello world node.js application using console
based method:
• Use the Node.js console module to print output on your system
console.
• Create a JavaScript file nodejs_hello_console.js using the below
content.
console.log('Hello World');
• Execute the script using the node
$node nodejs_hello_console.js
• [output]
Hello World!
2. Creating a simple hello world node.js
application using web based method:
A Node.js web application is build with 3 parts.
– Import module to create web server
– Create a web server
– Read client requests and send response back to
client
• Using http module: http module creates a web
server similar to Apache or Nginx web servers.
• Create a server with specified host and port.
• Create a JavaScript file nodejs_hello_web.js
and add the following content.
const http = require('http'); // Import the http module
const host = '0.0.0.0'; // Server will listen on all network interfaces
const port = 3000; // Port number for the server
// Create an HTTP server
const server = http.createServer((req, res) => {
res.statusCode = 200; // Set status code to OK
res.setHeader('Content-Type', 'text/plain'); // Set content type to
plain text
res.end('Hello World!'); // Send "Hello World!" as the response
});
// Start the server
server.listen(port, host, () => {
console.log(`Web server running at http://${host}:${port}`); //
Log server's address
});
• Execute the script using node. It will start a
web server on specified port and host.
node nodejs_hello_web.js
• Output
– The output "Server running on
http://localhost:3000" will appear in the terminal.
– Open your web browser and go
to http://localhost:3000. You should see "Hello
from the Node.js web app!" displayed.
– To stop the web server, press Ctrl+C in the
terminal.
Events
• An event in NodeJS is an action or occurrence, such
as a user click, a file being read, or a message being
received, that NodeJS can respond to.
• Events are managed using the EventEmitter class,
which is part of NodeJS's built-in events module. This
allows NodeJS to react to various actions
asynchronously.
• Node.js uses an event-driven architecture where
objects called "emitters" emit named events that
cause function objects ("listeners") to be called.
How Do Events Work in NodeJS?
1. Event-Driven Model
NodeJS uses an event-driven approach, meaning it waits for
events (such as a user action or data) to occur and then takes
action when those events happen.
2. EventEmitter
An EventEmitter is an object that can generate events in NodeJS.
You can set up "listeners" that wait for these events to happen
and then run a function (called a callback) when the event
occurs.
3. Event Loop
The event loop is a mechanism that runs in the background,
continuously checking for events.
When an event occurs, the event loop triggers the callback
function that was registered for that event.
• How does Event
Emitter work?
• Event Emitter
emits the data in
an event
called message
• A Listened is
registered on the
event message
• when
the message eve
nt emits some
data, the listener
will get the data.
Building Blocks of Event Emitter
.emit() - this method in event emitter is to emit an
event in module
.on() - this method is to listen to data on a
registered event in node.js
.once() - it listen to data on a registered event only
once.
.addListener() - it checks if the listener is registered
for an event.
.removeListener() - it removes the listener for an
event.
Steps involved in event handling in Node.js API
• First, import the events module, and declare an object of
EventEmitter class
// Import events module
var events = require('events');
// Create an eventEmitter object
var eventEmitter = new events.EventEmitter();
• Bind an event handler with an event with the following syntax −
// Bind event and event handler as follows
eventEmitter.on('eventName', eventHandler);
• To fire the event programmatically −
// Fire an event
eventEmitter.emit('eventName');
• Example that binds two listeners to the on event of
EventEmitter class
// Import events module
var events = require('events');

// Create an eventEmitter object


var eventEmitter = new events.EventEmitter();

// Create an event handler as follows


var connectHandler = function connected()
{ console.log('connection successful.'); }

// Bind the connection event with the handler


eventEmitter.on('connection', connectHandler);
// Bind the data_received event with the anonymous function
eventEmitter.on('data_received', function(){ console.log('data
received successfully.'); });

// Fire the connection event eventEmitter.emit('connection');

// Fire the data_received event


eventEmitter.emit('data_received'); console.log("Program
Ended.");

• Output
connection successful.
data received successfully.
Program Ended.
Listeners
• How are event listeners created
– An array containing all eventListeners is
maintained by Node. It is called
the listeners array.
– A new event listener is added to that array.
Syntax:
eventEmitter.addListener(event, listener)
eventEmitter.on(event, listener)
eventEmitter.once(event, listener) // listeners is
invoked only once and never again
– When the concerned event is emitted, each
eventListener that is present in the array is called
in a sequential or synchronous manner.
– The event listeners are called in a synchronous
manner to avoid logical errors, race conditions
etc.
– The total number of listeners that can be
registered for a particular event, is controlled by a
variable named maxListeners.
– It can be set using a function
called .setMaxListeners(n). Where n is any
number. Eg: emitter.setMaxlisteners(12); where
n=12
– The default number of listeners is 10. It is set by a
variable named defaultMaxListeners.
• Managing Event Listeners
– It is important to detach an event Listener once
its no longer needed to avoid memory leaks.
– Functions
like .removeListener(), .removeAllListeners()
enable the removal of listeners from the listeners
Array.
Syntax:
eventEmitter.removeListener(event, listener)
eventEmitter.removeAllListeners([event])
Timers
• The timers module contains functions that can execute code
after a certain period of time.
• Timers module is mainly categorized into two categories
• Scheduling Timers − This timer schedules the task to take
place after a certain instant of time.
– setImmediate()
– setInterval()
– setTimeout()
• Cancelling Timers − This type of timers cancels the
scheduled tasks which is set to take place.
– ClearImmediate()
– clearInterval()
– clearTimeout()
1. setTimeout() Method : Schedules the code
execution after a designated number of
milliseconds.
Syntax: setTimeout(function, delay, [args])
setTimeout(function ()
{ // Will be printed after 2 seconds return
console.log(‘Hello’);
}, 2000);
// This will be printed immediately
console.log('Executing setTimeout() method');
• Output
Executing setTimeout() method
Hello
2. setImmediate() Method: executes the code at the end of the
current event loop cycle.
Syntax: setImmediate(function, [args])
// Setting timeout for the function
setTimeout(function () { console.log('setTimeout() function running'); },
5000);
// Running this function immediately before any other
setImmediate(function () { console.log('setImmediate() function
running'); });
// Directly printing the statement
console.log('Simple statement in the event loop');
Output
Simple statement in the event loop
setImmediate() function running
setTimeout() function running
3. setInterval() Method: executes the code after
the specified interval. The function is executed
multiple times after the interval has passed. The
function will keep on calling until the process is
stopped externally or using code after specified
time period.
Syntax: setInterval(function, delay, [args])
setInterval(function() { console.log(‘Hello'); }, 1000);
Output
Hello
Hello…
4.clearImmediate() Method: Clears the
Immediate timer object that is created by
the setImmediate() method.
Syntax: clearImmediate(timer)
var timer = setImmediate(function A()
{ console.log("Timer set"); });
clearImmediate(timer);
console.log("Timer cancelled");
Output
Timer cancelled
5.clearInterval() Method: Clears the Immediate
timer object that is created by
the setInterval() method.
Syntax: clearInterval(timer)
var si = setInterval(function A() { return
console.log("Setting Intevals for 500 ms !"); },
500);
// Cleared the interval from 1000 ms
setTimeout(function()
{ clearInterval(si); }, 1000);
Output
Setting Intevals for 500 ms !
6.clearTimeout() Method: Clears the Immediate
timer object that is created by
the setTimeout() method.
Syntax: clearTimeout(timerObject)
var timer = setTimeout(function A() { return
console.log("Hello TutorialsPoint!"); }, 500);
// timer2 will be executed
var timer2 = setTimeout(function B() { return
console.log("Welcome to TutorialsPoint!"); }, 500);
clearTimeout(timer);
Output
Welcome to TutorialsPoint!
Callbacks
• A Callback in Node.js is an asynchronous
equivalent for a function.
• The callback is called when the function that
contains the callback as an argument
completes its execution, and allows the code
in the callback to run in the meantime.
• This makes Node.js highly scalable, as it can
process a high number of requests without
waiting for any function to return results.
Syntax of a callback in Node:
function function_name(argument, callback)
• How to Use Callbacks in Node:
Eg: Define a callback to print the error and result
after the function execution.
function function_name(argument, function
(error, result)
{
if(error){ console.log(error) }
else { console.log(result) }
})
• How to write a callback as a standard
function without a name: callback as a regular
function, using a function keyword then the
argument inside round brackets.
function function_name(argument, function
(callback_argument)
{ // callback body })
Eg: callback using the setTimeout function
setTimeout(function () { console.log('Callback as
Standard Function'); }, 1000);
• How to write a callback as an arrow function
It may be confusing to have multiple function
keywords in a block of code.
To eliminate the function keyword in the callback,
you can use an arrow function.
Syntax:
function function_name(argument,
(callback_argument) =>
{ // callback body })
Eg:
setTimeout(() => { console.log('Callback as Arrow
Function'); }, 1000);
Handling Data I/O
• Buffers
– Buffer is a way to store and manipulate binary
data in Node.js.
– Buffer is class that allows us to store raw data
similar to arrays.
– It is a global class so we can use it without any
need of importing a buffer module.
– Node.js provides the Buffer module, which allows
to create, read, write and manipulate binary data
in a buffer structure.
• Creation of Buffer
new Buffer(sizeInBytes)
new Buffer(octetArray)
new Buffer(string, [encoding])
var buffer = new Buffer(10);
• This will create a buffer of 10 units.
var buffer = new Buffer([1,2,3,4,5],"utf8");
• The second parameter which we have passed here is
encoding scheme. It allows various encodings such as
utf8(this is default one), ascii,ucs2,base64, or hex.
• Determining Buffer length
Buffer.byteLength(string,[encoding])
• Writing to Buffers
– You cannot extend the size of a Buffer object after
it has been created, but you can write data to any
location in the buffer.
write(string[,offset][,length][,encoding])
where
– string : It is the string to be written to the buffer.
– offset : It is the index from where we can start
writing. The default value is 0.
– length : It indicates the number of bytes to be
written to the buffer.
– Encoding : It indicates the desired encoding. The
default one is "utf8".
• Reading from Buffer
toString([encoding][,start][,end])
where
– encoding : It indicates the encoding scheme. The default one is
"utf8".
– start : Beginning index is indicated by this value. The default is 0.
– end : Ending index is indicated by this value.
• Example:
var buffer = new Buffer(50);
buffer.write("Good Morning");
console.log(buffer.toString('utf8'));
• Output
Good Morning
• Copying Buffers
buffer.copy(target, targetStart, sourceStart, sourceEnd);
– target Required. The array of buffers to concat
– targetStart Optional. A number specifying where to begin copying
to. Default 0
– sourceStart Optional. A number specifying where to begin copying
from. Default 0
– sourceEnd Optional. A number specifying where to stop copying
from. Default end of buffer
let buf1 = Buffer.from('abcdefghijkl');
let buf2 = Buffer.from('HELLO');
//Copy parts of buf2 into parts of buf1:
buf2.copy(buf1, 2, 0, 2);
console.log(buf1.toString());
Output
abHEefghijkl
• Concatenating Buffer: The concat() method joins all
buffer objects in an array into one buffer object.
Syntax: Buffer.concat(list, [totalLength])

const buf1 = Buffer.from('Hello');


const buf2 = Buffer.from(' ');
const buf3 = Buffer.from('World');
const bufferList = [buf1, buf2, buf3];

// Concatenate buffers without specifying totalLength


const concatenatedBuffer1 = Buffer.concat(bufferList);
console.log(concatenatedBuffer1.toString());
// Output: Hello World
// Concatenate buffers with specified
totalLength for performance
const totalLength = buf1.length + buf2.length +
buf3.length;
const concatenatedBuffer2 =
Buffer.concat(bufferList, totalLength);
console.log(concatenatedBuffer2.toString());
// Output: Hello World
Streams
• Stream can be defined as objects that reads data from
source or writes the data to the destination in continuous
fashion.
• The stream module in Node.js provides an abstraction for
working with streaming data.
• The stream is an EventEmitter instance that emits several
events. Following are the events that occur during stream
operations -
– data : This event is fired when we want to read the data from the
file.
– end : When there is no more data to read then this event is fired.
– error : If any error occurs during reading or writing data then this
event is fired.
– finish : When data is completely flushed out then this event
occurs.
• Accessing Streams:
const stream = require('stream');
• Types of Streams in Node.js:
– Writable: We can write data to these
streams. e.g., fs.createWriteStream().
– Readable: We can read data from these
streams. e.g., fs.createReadStream().
– Duplex: Streams that are both, Writable as well as
Readable. e.g., net.socket.
– Transform: Duplex streams that can modify or
transform data as it passes through.
e.g., zlib.createDeflate.
• Node.js fs module provides methods to work
with streams for efficient handling of large
files or continuous data flows.
• Creating a Readable Stream
const fs = require('fs');
const readableStream = fs.createReadStream('input.txt', 'utf8');
• Creating a Writable Stream
const fs = require('fs');
const writableStream = fs.createWriteStream('output.txt');
• Duplex Streams
stream.Duplex.call(this,opt);
Write Operation
• The steps that are followed to write data to the stream using node.js are as
follows
Step 1: Import the file stream module fs using require.
Step 2: Create a writable stream using the method createWriteStream.
Step 3: Write data to the stream using write method.
Step 4: Handle the events such as finish or error (if any)
Following Nodejs script shows how to write data to the string,
var fs = require("fs");
var str = "This is WAD Sesssion";
var ws = fs.createWriteStream('new.txt');
ws.write(str, 'utf8');
ws.end();
console.log("the data is written to the file...");
Read Operation
• For reading from the stream we use createReadStream. Then using the data
event the data can be read in chunks.
var fs = require("fs");
var str = "";
var rs = fs.createReadStream('sample.txt');
rs.setEncoding("utf8");

// handling stream event 'data'


rs.on('data', function(chunk) {
str += chunk;
}); //handling stream event'end'
rs.on('end', function() {
console.log(str)
}); //handling stream event 'error'
rs.on('error', function(err) {
console.log(err.stack);
});
Pipe Operation
• The pipe operation is a kind of operation in which output of one stream acts as
an input of another stream.
• There is no limit on pipe operation that means, all the output of one stream can
be fed as input to input to another stream.
Following are the steps used for using the pipe operation in your node.js program –
Step 1: Import the 'fs' module using require.
Step 2: Create readable stream using createReadStream function.
Step 3: Create writable stream using createWriteStream function.
Step 4: Use the pipe() function for passing the data from readable stream to
writable stream.
File System
• File system fs is implemented in the node.js
using require function.
var fs = require("fs");
• The common operations used with the file
system module are -
– Read file
– Create file
– Update file
– Delete file
READ FILE
• The read file operation can be performed synchronously or
asynchronously.
• For reading the file synchronously we use readFileSync
method. And for reading the file synchronously readFile
var fs = require("fs");
fs.readFile('input.txt',
function(err,data){
if(err)
console.log(err);
console.log(data.toString());
});
Create File
• Create We can create an empty file using the command open()
Syntax
open(path,flags[,mode],callback)
Where,
path : It is the path of the filename.
flag : It indicates, the behavior on opening a file. That
means “r” is open file for reading, "w" is for writing, “rs” is for
synchronous mode, "r+” or “w+“ means open a file for both read
and write purpose and so on.
mode: It indicates readable or writable mode.
Callback: It is basically a function which has two
arguments(err,data)
var fs = require("fs");
fs.open('fsfile.txt', 'w',
function(err, file) {
if (err)
console.log(err)
console.log('File
created!!!');
});
Update / Write File Operation
For writing to the file two operations are used most commonly –
1. appendFile()
2. writeFile()
• The appendFile(): method is used to write the contents at the
end of the specified file
var fs = require("fs");
str = "This line is written to the file";
fs.appendFile('myfile.txt', str,
function(err) {
if (err)
console.log(err)
console.log('File appended!!!');
});
• writeFile()
The writeFile() method is used to write the contents to
the file
var fs = require("fs");
str = "Thisline is replacing the
previous contents";
fs.writeFile('myfile.txt', str,
function(err) {
if (err)
console.log(err)
console.log('File Writing
Done!!!');
});
Delete file operation
• To delete the file, we use unlink() method.
Syntax
unlink(path, callback)
where
path : Is a path of the file to be deleted.
callback : It is a callback function with the only one argument for 'error’.
var fs = require("fs");
fs.unlink('fordel.txt', function(err) {
if (err)
throw err;
console.log("File is deleted!!!");
});
IMPLEMENTING HTTP SERVICES
• Processing URLs
– The URL module is one of the core modules in
Node.js.
– The URL module contains functions that help in
parsing a URL.
• import the URL module
const url = require('url');
• The url module provides two APIs,
– WHATWG URLs
– The traditional urls.
• The WHATWG URL standard is used by
browsers. The WHATWG URL API supports the
following:
– URL class : The URL class constructor is used to
create the url object in the following manner:
URL Object Properties
// Importing the url module
const { URL } = require("url");
//Creating url object with the URL() constructor.
const myurl = new URL(
"https://user1:[email protected]:81/sub?
id=134&num=2#block"
);
// Destructuring the myurl object.
const {
href,
origin,
protocol,
} = myurl;
console.log("Properties of url object");
//Print the url object.
console.log("Href value :", href);
console.log("Origin value :", origin);
console.log("Protocol value :", protocol);

• OUTPUT
Properties of url object
Href value
:https://user1:[email protected]:81/sub?
id=134&num=2#block
Origin value : https://www.example.com:81
Protocol value : https:
• The traditional url api is Node.js specific.
• It supports traditional url object properties
and urlObjectobject properties.
• The url.parse() method takes the url string as a parameter and
parses it.
• The url module returns an object with each part of the url as
property of the object.

url.parse(url_string, parse_query_string, slashes_host)


– url_string : <string> It is the URL string.
– parse_query_string : <boolean> It is a boolean value. By default, its
value is false. If it is set to true, then the query string is also parsed
into an object. Otherwise, the query string is returned as an unparsed
string.
– slashes_host : <boolean> It is a boolean value. By default, its value is
false. If it is set to true, then the token in between // and first / is
considered host.
// Importing the url module
const url = require("url");

//Using url.parse() method to get the url object.


const myurl = url.parse(
"https://www.scaler.com/topics/javascript/import-
js-file-in-js?query=scalar"
);

console.log(myurl);
Url {
protocol: 'https:',
slashes: true,
auth: null,
host: 'www.scaler.com',
port: null,
hostname: 'www.scaler.com',
hash: null,
search: '?query=scalar',
query: 'query=scalar',
pathname: '/topics/javascript/import-js-file-in-js',
path: '/topics/javascript/import-js-file-in-js?query=scalar',
href: 'https://www.scaler.com/topics/javascript/import-js-file-
in-js?query=scalar'
Query String Module
• In Node.js, query strings are a fundamental part of
handling data passed through URLs in HTTP requests.
• The Query String module used to provides utilities for
parsing and formatting URL query strings.
• It can be used to convert query string into JSON object
and vice-versa.
• They appear after a question mark (?) in a URL and consist
of key-value pairs separated by ampersands (&).
• For example, in https://example.com/search?
query=nodejs&page=2, query=nodejs&page=2 is the query
string.
• Install querystring using npm:
npm install querystring
• import querystring:
const querystring = require('querystring');
• querystring module: This module offers
methods for both parsing query strings into
JavaScript objects and stringifying JavaScript
objects back into query strings.
– Parsing: The querystring.parse() method converts a
query string into a JavaScript object
querystring.parse(query, sep, eq, options)
const querystring = require('querystring');
const qs = 'name=John&age=30';
const parsed = querystring.parse(qs);
console.log(parsed);
// Outputs: { name: 'John', age: '30' }
• Stringifying: The querystring.stringify()
method converts a JavaScript object into a query string.
querystring.stringify(obj, sep, eq, options)
const querystring = require('querystring');
const obj = { name: 'Jane', city: 'New York' };
const stringified = querystring.stringify(obj);
console.log(stringified);
// Outputs: name=Jane&city=New%20York
HTTP Module
• Node.js includes a powerful built-in HTTP module that
enables you to create HTTP servers and make HTTP
requests.
• Key Features
– Create HTTP servers to handle requests and send responses
– Make HTTP requests to other servers
– Handle different HTTP methods (GET, POST, PUT, DELETE,
etc.)
– Work with request and response headers
– Handle streaming data for large payloads
• Including the HTTP Module
const http = require('http');
• Creating an HTTP Server
// Create a server object
const server = http.createServer((req, res) => {
// Set the response HTTP header with HTTP status
and Content type
res.writeHead(200, { 'Content-Type': 'text/plain' });

// Send the response body as 'Hello, World!'


res.end('Hello, World!\n');
});
1. The http.ClientRequest object in Node.js
• It represents an outgoing HTTP request that is being
sent from a client to a server.
• It is an instance of a Writable stream and is created
internally when http.request() or http.get() are called.
http.request(options, callback)

2. The http.serverResponse object


• The ServerResponse object represents the outgoing
response from the server to the client.
• This object provides methods and properties for
constructing and sending the HTTP response.
3. The http. IncomingMessage Object
• The IncomingMessage object represents the request to the
server.
• Created by either the HTTP server or HTTP client.

4. The HTTP Server Object:


• To start, create a Server object using
http.createServer([requestListener])
• To listen, call
listen(port, [hostname], [backlog], [callback]) on the Server object

5. Serving Static Files


• Serving static files in Node.js, such as images, CSS, and
JavaScript, is commonly achieved using the Express.js framework
and its built-in express.static middleware.
6. Implementing Dynamic GET Servers
• Implement code in the request handler to
dynamically populate data, write to the response,
and call

7. Implementing POST Servers


• Implement code in the request handler to read
and process the POST body contents.
• After processing, dynamically populate data,
write to the response, and call end()
• Output can be a webpage, HTTP snippet, JSON
data, or other data
8. Creating an HTTPS Client
• Creating an HTTPS client in Node.js primarily involves
using the built-in https module.
• For simple GET requests, the https.get() method is a
convenient choice:
https.get('https://jsonplaceholder.typicode.com/users?
_limit=2', (res) => {
let data = '';

9. Creating an HTTPS Server


• Creating an HTTPS server is almost exactly like creating an
HTTP server
• The most important options are key and cert

You might also like