Unit - 2 Notes FSW

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 29

UNIT – 2

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 is an open-source, cross-platform JavaScript runtime environment used


for executing JavaScript code outside of a web browser. We often use NodeJS
for building back-end services like APIs, Web App, or Mobile App. It’s utilized in
production by large companies like Paypal, Uber, Netflix, Walmart, etc.

 Node.js is an open source server environment


 Node.js is free
 Node.js runs on various platforms (Windows, Linux, Unix, Mac OS X,
etc.)
 Node.js uses JavaScript on the server

Here is how Node.js handles a file request:

1. Sends the task to the computer's file system.


2. Ready to handle the next request.
3. When the file system has opened and read the file, the server returns the
content to the client.

Node.js eliminates the waiting, and simply continues with the next request.

What Can Node.js Do?

 Node.js can generate dynamic page content


 Node.js can create, open, read, write, delete, and close files on the server
 Node.js can collect form data
 Node.js can add, delete, modify data in your database

Key Elements of Node js:


How does Node.js work?

Node.js accepts the request from the clients and sends the response, while working
with the request node.js handles them with a single thread. To operate I/O operations
or requests node.js use the concept of threads. Thread is a sequence of instructions
that the server needs to perform. It runs parallel on the server to provide the
information to multiple clients. Node.js is an event loop single-threaded language. It
can handle concurrent requests with a single thread without blocking it for one
request.

Concepts of Node.js
The following diagram depicts some important parts of Node.js that are useful and
help us understand it better.

Features of Node JS

Following is a list of some important features of Node.js that makes it the first
choice of software architects.

1. Extremely fast: Node.js is built on Google Chrome's V8 JavaScript


Engine, so its library is very fast in code execution.
2. I/O is Asynchronous and Event Driven: All APIs of Node.js library are
asynchronous i.e. non-blocking. So a Node.js based server never waits for
an API to return data. The server moves to the next API after calling it
and a notification mechanism of Events of Node.js helps the server to get
a response from the previous API call. It is also a reason that it is very
fast.
3. Single threaded: Node.js follows a single threaded model with event
looping.
4. Highly Scalable: Node.js is highly scalable because event mechanism
helps the server to respond in a non-blocking way.
5. No buffering: Node.js cuts down the overall processing time while
uploading audio and video files. Node.js applications never buffer any
data. These applications simply output the data in chunks.
6. Open source: Node.js has an open source community which has
produced many excellent modules to add additional capabilities to
Node.js applications.
7. License: Node.js is released under the MIT license.

Installation of Node.JS

 How to Download & Install Node.js on Windows 10


 How to uninstall Node.js on windows
 How to Install NPM on Windows 10
 Running your first "Hello World" application in Node.js

Prerequisites

Below we get started, here are a few system requirements to download,


install, and set up React-Native on Windows 10.

Hardware requirements
 RAM 4GB
 CPU Intel Core i3TM i3 HQ CPU @2.50 GHz
 ROM 256 GB
Software requirement
 Chocolatey

Installation procedure

 Step-by-step procedure to Install node.js on Windows 10

Undoubtedly, the first step to getting started on working with node.js is


installing the software package in your system. Once done, follow the step-
by-step tutorial on how to proceed to get the node.js framework successfully
installed in your system. We will also look at how you can uninstall the
program from your computer completely.
Step-1: Download node.js installer into your system

Visit the official node.js site https://nodejs.org/en/download/ and click on


Windows installer to download the necessary software in your system. The
installer contains the NPM package. Based on the system you want to install,
choose 32-bit installer or 64-installer and proceed.

Note: When you click on download, you will be asked to choose the file
location you want to store the instal.msi binary files. Choose a secure file
location of your choice.
Step-2: Run the installation

Once you choose the path, the next step is to double-click the
instal.msi binary files to initiate the installation process. Furthermore, you
will be asked for permission to run the application.

Warning: On the open file security warning, there is a cancel option as well.
Don't click on the cancel option, or else you may perhaps need to restart the
installation. You can use the back button to check your previous installation
step.

On running the application, you will proceed to an interface with a welcome


message. Click the "Next" button and proceed with the installation as shown
in the image.
Step-3: Accept the terms of usage

After clicking the next option, you will get an end-user license agreement.
Read the terms of using the software, and then click on next.

N.B. You will find a square box asking you to agree with the terms, and only
when you have read the terms, you will be allowed to proceed further.

Step-4: Specify the path

Once you have accepted the terms and conditions, the next step is to specify
the path where you want to install node.js. Your file location is the path where
you must install the node.js in your system. Before we proceed further, you
can enroll in Web Design Training to accelerate your career.

Once you have specified the path, click on the Next button to proceed with
the installation.
Step-5: Select the default options

On proceeding with the Next option, the custom page setup will open up on
the screen. Here you will get four icons as stated below:

 node.js runtime
 NPM package manager
 Online documentation shortcuts
 Add to PATH

Select all the options as default and then proceed with the Next option.

Step-6 Initiate the installation

After all these steps, you will see an install button to process the installation
of node.js on Windows. Click on the install button to initiate the installation
of node.js on your Windows. Based on your system performance it may take a
couple of minutes to install node.js on your system. Once the installation is
complete, you will get a message on your screen as — Node.js has been
successfully installed.
Step-7: Complete the installation

On clicking the Finish button, the process of installation of node.js is


successfully completed. Congratulations! You have successfully installed
node.js on your Windows 10.

Verifying the install

To verify that the node.js has been successfully installed in your system, go to
the command prompt and run it as administrator. Now use the following
command to check the node.js version installed in your system.
node -v
Copy Code

The message v14.16.1 verifies that node.js has been successfully installed on
your windows, and you are ready to use it.

Alternative Method

Do you know there is also an alternative way to download & install Node.js
and NPM on Windows 10? Using a software package manager called
Chocolatey, you can install node.js and NPM on your machine. Let us
understand how to install node.js and NPM on windows using
Chocolatey step by step. We will also look at how to uninstall the same with
Chocolatey.

Installing Chocolatey.

The first process that you need to do is to install Chocolatey in your system.
Take a note that the installation of Chocolatey requires administrator access to
the computer’s command prompt to run.

 Choose the option – get started as shown below:


 Once you go to the official Chocolatey website, select the individual as
shown in the picture.

 Open Windows PowerShell and run as administrator. Now run the


command and then press enter.
Get-Execution Policy
 On running this command, you will get a message as Restricted. Once
you get the message as Restricted, continue and then
run another command and press enter.
Set-Execution Policy All Signed

 You will get a screen with execution policy changes. Select the A (Yes to
all) option and then press Enter.

 Copy and paste the command mentioned below:


Set-ExecutionPolicy Bypass -Scope Process -
Force; [System.Net.ServicePointManager]::SecurityProtocol =[System.Net.Serv
icePointManager]::SecurityProtocol -bor 3072; iex ((New-Object System.Net.
WebClient).DownloadString('https://chocolatey.org/install.ps1'))
Copy Code

To check whether you have installed it well, open the command prompt below:

choco -version
Copy Code

If you have installed it well, you will see the display of the Chocolatey
version you have installed on the screen as below:
Boom! Chocolatey is now successfully installed in your system.
Install Node.js

Using Chocolatey that you have just installed, now we can install Node.js in
the system. Open the command prompt as the administrator and put in the
Chocolatey command prompt as mentioned below:

Choco install -y nodejs.install


Copy Code

To confirm if it has installed correctly on the computer, you need to execute


the command below on the computer command prompt, as an administrator:

node --version
Copy Code
If you have followed the steps correctly, the installation would have been
successful and the message below will display on your screen after the
installation has been completed.

After installing the Node.js, the Node Package Manager NPM automatically
gets installed in the system. Run the command below to check the installation
of NPM. The displayed message below verifies that the installation of NPM is
successful.
Writing your first program on node.js

Now that you have successfully downloaded and installed node.js in your
system, let’s learn how to write a program using node.js

Follow the steps to write your first program.

 Step-1: Create a folder and name it. (Here we have created a folder
named Node Programs.
 Step-2: Open any code editor of your choice (here we are using Visual
Studio Code).
 Step-3: Click on the file menu and open the folder you just created.

 Step-4: Once you open the folder, create a file and name it. (Here we
have created a file named as welcome.js)
 Step-5: Write your program and save it using (Ctrl + S).
 Step-6: Start debugging using the shortcut f5.

You have successfully created your first project using node.js.


Implementing HTTP services in Node.js
Step 1: Import HTTP module
Let’s start by creating a new empty file server.js and import the Node.js module http
with the following line of code:

const http = require(“http”);

Step 2: Create Variables For Host And Port


Next we’re defining two variables which are holding information of host and port on
which the HTTP server should be running. Add the following two lines of code to
server.js:

const host = ‘localhost’;

const port = 8000;

Step 3: Create A Server Process


In the next step we’re ready to create the server by using method createServer of the
http module:

const server = http.createServer(requestListener);

server.listen(port, host, () => {

console.log(`Server is running on http://${host}:${port}`);

});

As you can see we’re heading over a function with name requestListener. This
function will be implemented in the next step and is containing the logic to handle
incoming HTTP requests.

The created server instance is stored in server. To start the server process we need to
call server.listen. This method is receiving three arguments: port, host and a callback
function which is executed once the server process is up and running. In the example
we’re using this function to output information to the user.

Step 4: Implement the requestListener function


The requestListener function has been handed over when we created the HTTP
server by using method createServer is the previous step. Now we need to add the
missing implementation for requestListener into server.js:

const requestListener = function(req, res) {

res.writeHead(200);

res.end(“Hello World from Node.js HTTP Server”);

The requestListener function is expecting to get two arguments: req and res. With
req we have access to the request object and with res we have access to the
corresponding response object.

Inside the method we’re using the res argument to first set the HTTP header status of
the response to value 200 (by using method writeHead. Second we’re using the
method end to send back a text message to the client.

Finally let’s take a look at the complete implementation in server.js:

const http = require("http");

const host = 'localhost';

const port = 8000;

const requestListener = function(req, res) {

res.writeHead(200);
res.end("Hello World from Node.js HTTP Server");

const server = http.createServer(requestListener);

server.listen(port, host, () => {

console.log(`Server is running on http://${host}:${port}`);

});

Step 5: Start And Test The HTTP Server


With the complete implementation in place we’re ready to start the server process
with the following command:

$ node server.js

You should then be able to see the following output:

To test if the server process is responding and sending back the text message let’s
use the curl command in the following way:
Handling Data I/O
Most active web applications and services have a lot of data flowing through
them. These data include text, JSON strings, binary buffers, and data streams.
Therefore, Node.js has many built-in mechanisms to handle data I/O from one
system to another.

1. Working with JSON


JavaScript Object Notation, referred to as JSON is One of the most common
data types you will use when implementing Node.js web applications and
services
The simplicity of the JSON syntax makes it very easy for humans and machines
to read and write.
Reading a JSON file:
 Method 1: Using require method: The simplest method to read a
JSON file is to require it in a node.js file using require() method.

const data = require('path/to/file/filename');


Serialization is the process of modifying an object or data structure to a format
that is easy to store or transfer over the internet. You can recover the serialized
data by applying the reverse process.

Deserialization refers to transforming the serialized data structure to its original


format.

You will almost always need to serialize JSON or JavaScript object to a JSON
string in Node. You can do so with the JSON.stringify method before writing it
to a storage device or transmitting it over the internet:

const config = { ip: '1234.22.11', port: 3000};


console.log(JSON.stringify(config));

On the other hand, after reading the JSON file, you will need to deserialize the
JSON string to a plain JavaScript object using the JSON.parse method before
accessing or manipulating the data:

const config = JSON.stringify({ ip: '1234.22.11', port: 3000});


console.log(JSON.parse(config));
JSON.stringify and JSON.parse are globally available methods in Node. You
don’t need to install or require before using.
2. Use the Buffer module to buffer data

Although JavaScript may be very Unicode friendly, it is not very good at


managing binary data. However, binary data is very useful when implementing
some web applications and services, such as:

 Transfer compressed files.


 Generate moving images
 Send serialized binary data
Buffered data is composed of a series of big-endian or little-endian format
bytes. This means that they take up less space than text data. Therefore, Node.js
provides the Buffer module, which allows you to construct, read, write, and
manipulate binary data in the buffer structure. The Buffer module is global, so
you don't need to use the require() function to access it.

Create a buffer

The Buffer object is actually the most primitive memory allocation area.
Therefore, you must determine its size at the time of creation. There are 3 ways
to create a Buffer object using the new keyword:

1. new Buffer(sizeInBytes)
2. new Buffer(octetArray)
3. new Buffer(string,[encoding])

After the Buffer object has been created, you cannot expand its size, but you can
write data to any location in the buffer.

Here are some code examples:

1. buf256 = new Buffer(256);


2. buf256.fill(0);
3. buf256.write("xiaobaicai hello!");
4. console.log(buf256.toString());
5. buf256.write("more text",9,9);
6. console.log(buf256.toString());
7. Read from the buffer
Method Explanation

Returns a string
that contains the
characters from
the start index to
the end index to
buffer.toString([encoding],[start],
the end index of
[end])
the buffer,
decoded by the
encoding
specified by
encoding

Returns the
decoded string
stringDecoder.write(buffer)
version of the
buffer

Returns the octal


value of the buffer
buffer(offset)
at the specified
offset (offset) byte

readInt8(offset,[noAssert])

Determine the buffer length

Use Buffer.byteLength(string,[encoding]) to determine the length of the buffer


byte, and add .length directly to get the length of the string.

1. "UTF8 text \u00b6".length;


2. //The calculation result is 11
3. Buffer.byteLength("UTF8 text \u00b6");
You can also copy the data in one buffer to another buffer by direct indexing,
for example in the following example:

sourceBuffer[index] = destinationBuffer[index]

Slicing the buffer

Use slice([start],[end]) to slice

(8) Splicing buffer

You can concatenate multiple buffers using concat(list,[totalLength])

3. Use the Stream module to transfer data

The Stream module is an important module of Node.js. The data stream is a


readable, writable, or both readable and writable memory structure. Streaming
is widely used in Node.js, it is used to access files, read data from HTTP
requests, and other fields.

(1) Readable stream

The Readable stream is designed to provide a mechanism to easily read data


entering the application from other sources. Some common examples of
Readable streams are:

 HTTP response on the client.


 HTTP request on the server.
 fs read stream
 zlib stream
 crypto stream
 TCP socket
 Stdout and stderr of the child process
 process.stdin
2) Writeable stream

The Writeable stream is designed to provide a mechanism for writing data in a


form that can be easily used in another area of the code. Some common
examples of Writable streams are:

 HTTP request on the client


 HTTP request on the server
 fs write stream
 zlib stream
 crypto stream
 TCP socket
 Stdin of the child process
 process.stdout and process.stderr.

(3) Duplex flow

Duplex (two-way) stream is a stream that combines readable and writable


functions. A good example of Duplex flow is TCP socket connection.

(4) Transform flow

The Tramsform (transformation) stream extends the Duplex stream, but it


modifies the data between the Writable stream and the Readable stream. This
stream type can be very useful when you need to modify data from one system
to another. Some strengths of Transform flow are as follows:

 zlib stream
 crypto stream

You might also like