Full Stack Web Development - IT3501 - Notes - Unit 2 - Node JS (1)
Full Stack Web Development - IT3501 - Notes - Unit 2 - Node JS (1)
enter. Environmental
Professional English Sciences
Professional and Sustainability -
English - I - - II - HS3252 Discrete GE3451
HS3152 Mathematics -
Statistics and MA3354 Theory of
Numerical Computation
Matrices and
Methods - MA3251 Digital Principles
Calculus - CS3452
and Computer
- MA3151 Engineering Organization
Semester
Artificial
Semester
Semester
- CS3351
Semester
Graphics Intelligence and
Engineering Machine Learning
Physics - PH3151 - GE3251
Foundation of - CS3491
Data Science -
Physics for CS3352
2nd
Database Management
1st
Engineering Information
3rd
4th
Science System - CS3492
Chemistry
- PH3256 Data Structures and
- CY3151 Algorithms - CD3291
Web Essentials -
Basic Electrical and
Electronics IT3401
Problem Solving Engineering - BE3251 Object Oriented
and Python Programming - Introduction to
Programming - CS3391 Operating
Programming in C -
GE3151 Systems - CS3451
CS3251
Computer Networks
-
CS3591 Object Oriented
Software Human Values and
Full Stack Web Engineering - Ethics - GE3791
CCS356
Development -
Project Work /
Semester
Semester
Semester
Open Intership
Distributed Open Elective 3
Elective-1
Computing
Open Elective 4
7th
8th
- CS3551 Elective-3
5th
6th
Elective-4 Management
Embedded Systems
and IoT - CS3691
Elective-5 Elective
Elective 1
Elective-6
Elective 2
All Computer Engg [ B.E., M.E., ] (Click on Subjects to
Subjects - enter)
Programming in C Computer Operating Systems
Networks
Programming and Data Programming and Problem Solving and
Structures I Data Python
Structure II Programming
Database Management Computer Analog and Digital
Systems Architecture Communication
Design and Analysis of Microprocessors and Object Oriented
Algorithms Microcontrollers Analysis
and Design
Software Engineering Discrete Internet Programming
Mathematics
Theory of Computation Computer Graphics Distributed Systems
Mobile Computing Compiler Design Digital Signal
Processing
Artificial Intelligence Software Testing Grid and Cloud
Computing
Data Ware Housing and Cryptography and Resource
Data Mining Network Security Management
Techniques
Service Oriented Embedded and Real Multi - Core
Architecture Time Systems Architectures and
Programming
Probability and Queueing Physics for Transforms and
Theory Information Partial
Science Differential
Equations
Technical English Engineering Engineering Chemistry
Physics
Engineering Graphics Total Quality Professional Ethics in
Management Engineering
Basic Electrical and Problem Solving Environmental Science
Electronics and and Python and Engineering
Measurement Engineering Programming
www.BrainKart.
com
Web Servers
Web pages are a collection of data, including images, text files, hyperlinks, database files
etc., all located on some computer (also known as server space) on the Internet. A web server
is dedicated software that runs on the server-side. When any user requests their web browser
to run any web page, the webserver places all the data materials together into an organized
web page and forwards them back to the web browser with the help of the Internet.
Therefore, we can conclude that: -
A web server is a dedicated computer responsible for running websites sitting out on those computers
somewhere on the Internet. They are specialized programs that circulate web pages as summoned by
the user. The primary objective of any web server is to collect, process and provide web pages to the
users.
This intercommunication of a web server with a web browser is done with the help of a
protocol named HTTP (Hypertext Transfer Protocol).
These stored web pages mostly use static content, containing HTML
documents, images, style sheets, text files, etc. However, web servers can serve static as well as
dynamic contents. Web Servers also assists in emailing services and storing files. Therefore it
also uses SMTP (Simple Mail Transfer Protocol) and FTP (File Transfer Protocol)
protocols to support the respective services. Web servers are mainly used in web hosting or hosting
the website's data and running web-based applications.
The hardware of the web servers are connected to the Internet that manages the data exchange facility
within different connected devices. In contrast, the software of web server software is responsible for
controlling how a user accesses delivered files. Typically, web server management is an ideal
example of the client/server model. Therefore, it is compulsory for all computers that host
websites (whether with state or dynamic web page content) to have web server software.
https://play.google.com/store/apps/details? Page: 1 / 37
www.BrainKart.
com
1. On the hardware side, a web server is defined as a computer that stores software and
another website raw data, such as HTML files, images, text documents, and JavaScript files.
The hardware of the web servers are connected to the web and supports the data exchange
with different devices connected to the Internet.
2. On the software side, a web server includes server software accessed through website
domain names. It controls how web users access the web files and ensures the supply of
website content to the end-user. The web server contains several components, including an
HTTP server.
Let's discover the step-by-step process of what happens whenever a web browser approaches
the web server and requests a web file or file. Follow the below steps:
https://play.google.com/store/apps/details? Page: 2 / 37
www.BrainKart.
com
1. First, any web user is required to type the URL of the web page in the address bar of your
web browser.
2. With the help of the URL, your web browser will fetch the IP address of your
domain name either by converting the URL via DNS (Domain Name System) or by looking
for the IP in cache memory. The IP address will direct your browser to the web server.
3. After making the connection, the web browser will request for the web page from the web
server with the help of an HTTP request.
4. As soon as the web server receives this request, it immediately responds by sending back
the requested page or file to the web browser HTTP.
5. If the web page requested by the browser does not exist or if there occurs some error in
the process, the web server will return an error message.
6. If there occurs no error, the browser will successfully display the webpage.
Many Web servers, even the basic one, also support the server-side scripting technique. Server-side
scripting is a web development method used to employ scripts on a web server that produces a
customized response for each user. This technique operates on the server machine and consists of an
extensive feature set, including database access. The server-side scripting process will have various
scripting languages such ASP
, PHP
, Java
, JavaScript
, Python
, ruby
and many more. This technique also enables the HTML files to be created dynamically.
https://play.google.com/store/apps/details? Page: 3 / 37
www.BrainKart.
com
1 Static web servers refer to the servers, Dynamic web servers refer to the servers where
which serve only the static content i.e., the content of the page can be updated and
the content is fixed and being shown as altered.
it is.
2 A static web server includes a computer A dynamic web server also includes a computer
and the HTTP (Hyper Text Transfer with plenty of other software, unlike an
Protocol) software. application server and database model.
3 It is called static; the web pages content It is called dynamic because the application
won't change unless the user manually server is used to update the web pages files at
changes it, and the server will deliver the server-side, and due to which, it can change
web files as is to the web browser. on every call requested by the web browser.
4 Static web servers take less time to load The Dynamic web server can only produce the
the data. data when it is requested from the database.
Therefore, it is time consuming and more
complicated when compared to static web
servers.
3. Nginx
Nginx is an open-source web server commonly used by administrators as it
supports light resource application and scalability.
https://play.google.com/store/apps/details? Page: 4 / 37
www.BrainKart.
com
4. Lighttpd
Lighttpd, also known as lighty, is a free, open-source web server with the
FreeBSD operating system. This web server is fast, secure and consumes much
less CPU power. It can also run on the commonly used operating system, unlike
Windows, Mac OS X, Linus.
Node.js Tutorial
Node.js tutorial provides basic and advanced concepts of Node.js. Our Node.js tutorial is
designed for beginners and professionals both.
Node.js is a cross-platform environment and library for running JavaScript applications
which is used to create networking and server-side applications.
Our Node.js tutorial includes all topics of Node.js such as Node.js installation on windows
and linux, REPL, package manager, callbacks, event loop, os, path, query string,
cryptography, debugger, URL, DNS, Net, UDP, process, child processes, buffers, streams,
file
https://play.google.com/store/apps/details? Page: 5 / 37
www.BrainKart.
com
systems, global objects, web modules etc. There are also given Node.js interview questions to
help you better understand the Node.js technology.
What is Node.js
Node.js is a cross-platform runtime environment and library for running JavaScript
applications outside the browser. It is used for creating server-side and networking web
applications. It is open source and free to use.
Many of the basic modules of Node.js are written in JavaScript. Node.js is mostly used to run
real-time server applications.
The definition given by its official documentation is as follows:
?Node.js is a platform built on Chrome's JavaScript runtime for easily building fast and
scalable network applications. Node.js uses an event-driven, non-blocking I/O model that
makes it lightweight and efficient, perfect for data-intensive real-time applications that run
across distributed devices.?
Node.js also provides a rich library of various JavaScript modules to simplify the
development of web applications.
1. Node.js = Runtime Environment + JavaScript Library
Different parts of Node.js
The following diagram specifies some important parts of Node.js:
Features of Node.js
Following is a list of some important features of Node.js that makes it the first choice of
software architects.
https://play.google.com/store/apps/details? Page: 6 / 37
www.BrainKart.
com
NPM
What is npm
npm is a short form of Node Package Manager, which is the world's largest software
registry. The open-source web project developers use it from the entire world
to share and borrow packages. The npm also acts as a command-line utility for the Node.js
project for installing packages in the project, dependency management, and even version
management.
Components of npm
npm mainly consists of three different components, these are:
1. Website: The npm official website is used to find packages for your project, create and set up
profiles to manage and access private and public packages.
2. Command Line Interface (CLI): The CLI runs from your computer's terminal to interact
with npm packages and repositories.
3. Registry: The registry is a large and public database of JavaScript projects and
meta-information. You can use any supported npm registry that you want or even your own.
You can even use someone else's registry as per their terms of use.
https://play.google.com/store/apps/details? Page: 7 / 37
www.BrainKart.
com
npm installation is highly recommended using nvm (Node Version Manager) rather than using
Node installer. The Node installation process installs npm in the directory by allowing local
permissions, and it generates an error message when you try to run npm packages globally.
https://play.google.com/store/apps/details? Page: 8 / 37
www.BrainKart.
com
6. Select the destination location where you want to install NVM and click on the Next button.
We leave it as the default selected location.
7. Select the folder location in which the setup will create the symlink and click on
the Next button.
https://play.google.com/store/apps/details? Page: 9 / 37
www.BrainKart.
com
8. Now, your setup is ready to install, click on the Install button to start the installation process.
9. Now, the nvm-setup is installed on your personal computer, and it will take few seconds to
wait to complete it.
https://play.google.com/store/apps/details? Page: 10 / 37
www.BrainKart.
com
10. Your nvm setup installation gets finished; click on the Finish button to exit from setup.
You can also check the nvm version using the command: nvm version.
https://play.google.com/store/apps/details? Page: 11 / 37
www.BrainKart.
com
In the above list, CURRENT refers to the current version of Node.js, and LTS refers to the
long-term support version.
This command installs Node.js (64-bit or 32-bit) and npm together depending on your device.
https://play.google.com/store/apps/details? Page: 12 / 37
www.BrainKart.
com
Currently, we have the Node.js version (14.15.4) running on our device. We can also be able
to install more different versions of Node.js on a computer if required (while building another
Node.js project based on a different version). To install another version of Node.js, choose a
version from the nvm list available and run the command given below.
1. nvm install 12.20.2
https://play.google.com/store/apps/details? Page: 13 / 37
www.BrainKart.
com
Here, we have selected another Node version 12.20.2 to install, and it also downloads and installs
compatible npm on our device.
Now, we have two different versions of Node.js and npm. To check the total number of installed
Node.js version, run the following command:
1. nvm list
Now, we have two different versions of Node.js and npm on our computers.
https://play.google.com/store/apps/details? Page: 14 / 37
www.BrainKart.
com
Depending on your computer operating system and its bits, download any supported Node.js
installer.
1. We have Windows with the 64-bit operating system, and we are downloading a 64-bit
Node.js installer for our device.
2. After downloading, run the setup and follow the installation instruction as shown on the
screen.
https://play.google.com/store/apps/details? Page: 15 / 37
www.BrainKart.
com
4. Read the end-user license agreement, accept it and click on the Next button.
https://play.google.com/store/apps/details? Page: 16 / 37
www.BrainKart.
com
5. Choose a custom location of your Node.js and click on Next to install. We keep it as its
default location.
6. Select the feature of Node.js to get installed and click on Next. We keep it as its default
feature provided.
https://play.google.com/store/apps/details? Page: 17 / 37
www.BrainKart.
com
7. If you want to install some other necessary tools (C/C++, Chocolaty) with your node.js and
npm, checkmark the box and click on the Next button.
8. Now, click on the Install button to install Node.js, which also installs npm on your device.
https://play.google.com/store/apps/details? Page: 18 / 37
www.BrainKart.
com
The additional tools are ready to install, as we marked above to install additional tools
automatically. Press any key to continue.
Run the following command on the command line to download the latest version of npm.
1. npm install -g npm
Properties of npm:
o All npm packages are defined in files called package.json.
o You must write the content of package.json in JSON.
o At least two fields must be present in the definition file: name and version.
https://play.google.com/store/apps/details? Page: 19 / 37
www.BrainKart.
com
package.json
package.json file will be generated when we run the npm init to initialize
a JavaScript/Node.js project with the basic metadata information provided by
developers:
name: it is the name of your JavaScript library/project
version: it is the version of your project
description: pass the project's description information
license: it is a project's license
https://play.google.com/store/apps/details? Page: 20 / 37
www.BrainKart.
com
}).listen(8080);
This example takes the path requested and it serves that path, relative to the local directory. This
works fine as a quick solution; however, there are a few problems with this approach. First, this code
does not correctly handle mime types. Additionally, a proper static file server should really be taking
advantage of client side caching, and should send a "Not Modified" response if nothing has changed.
Furthermore, there are security bugs that can enable a malicious user to break out of the current
directory. (for example, GET /../../../).
Each of these can be addressed individually without much difficulty. You can send the proper mime
type header. You can figure how to utilize the client caches. You can take advantage
of path.normalize to make sure that requests don't break out of the current directory. But why write all
that code when you can just use someone else's library?
There is a good static file server called node-static written by Alexis Sellier which you can leverage.
Here is a script which functions similarly to the previous one:
var static = require('node-static');
var http = require('http');
https://play.google.com/store/apps/details? Page: 21 / 37
www.BrainKart.
com
https://play.google.com/store/apps/details? Page: 22 / 37
www.BrainKart.
com
https://play.google.com/store/apps/details? Page: 23 / 37
www.BrainKart.
com
https://play.google.com/store/apps/details? Page: 24 / 37
www.BrainKart.
com
https://play.google.com/store/apps/details? Page: 25 / 37
www.BrainKart.
com
app.use(express.static('public'));
https://play.google.com/store/apps/details? Page: 26 / 37
www.BrainKart.
com
Save the above code in a file named server.js and run it with the following command.
$ node server.js
Now open http://127.0.0.1:8081/images/logo.png in any browser and see observe following
result.
GET Method
Here is a simple example which passes two values using HTML FORM GET method. We are
going to use process_get router inside server.js to handle this input.
<html>
<body>
</body>
</html>
Let's save above code in index.htm and modify server.js to handle home page requests as
well as the input sent by the HTML form.
var express =
require('express'); var app =
express();
app.use(express.static('public'));
app.get('/index.htm', function (req, res) {
res.sendFile( dirname + "/" + "index.htm" );
})
https://play.google.com/store/apps/details? Page: 27 / 37
www.BrainKart.
com
First Name:
Last Name:
SUBMIT
Bottom of Form
Now you can enter the First and Last Name and then click submit button to see the result and
it should return the following result −
{"first_name":"John","last_name":"Paul"}
POST Method
Here is a simple example which passes two values using HTML FORM POST method. We
are going to use process_get router inside server.js to handle this input.
<html>
<body>
</body>
</html>
https://play.google.com/store/apps/details? Page: 28 / 37
www.BrainKart.
com
Let's save the above code in index.htm and modify server.js to handle home page requests as
well as the input sent by the HTML form.
var express =
require('express'); var app =
express();
var bodyParser = require('body-parser');
app.use(express.static('public'));
app.get('/index.htm', function (req, res) {
res.sendFile( dirname + "/" + "index.htm" );
})
First Name:
Last Name:
SUBMIT
Bottom of Form
Now you can enter the First and Last Name and then click the submit button to see the
following result −
{"first_name":"John","last_name":"Paul"}
https://play.google.com/store/apps/details? Page: 29 / 37
www.BrainKart.
com
File Upload
The following HTML code creates a file uploader form. This form has method attribute set
to POST and enctype attribute is set to multipart/form-data
<html>
<head>
<title>File Uploading Form</title>
</head>
<body>
<h3>File Upload:</h3>
Select a file to upload: <br />
</body>
</html>
Let's save above code in index.htm and modify server.js to handle home page requests as
well as file upload.
var express =
require('express'); var app =
express();
var fs = require("fs");
app.use(express.static('public'));
app.use(bodyParser.urlencoded({ extended: false }));
app.use(multer({ dest: '/tmp/'}));
https://play.google.com/store/apps/details? Page: 30 / 37
www.BrainKart.
com
} else
{ response =
{
message:'File uploaded successfully',
filename:req.files.file.name
};
}
console.log( response );
res.end( JSON.stringify( response ) );
});
});
})
https://play.google.com/store/apps/details? Page: 31 / 37
www.BrainKart.
com
Rendering Templates
FoalTS provides a minimalist template engine to render templates. This engine replaces all
the occurrences of S myVariableName }} with the given values.
Here is an example showing how to use it:
templates/index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>{{ title }}</title>
</head>
<body>
Hello {{ name }}!
</body>
</html>
src/app/app.controller.ts
import { Get, render } from '@foal/core';
https://play.google.com/store/apps/details? Page: 32 / 37
www.BrainKart.
com
Output (GET /)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Home</title>
</head>
<body>
Hello Alix!
</body>
</html>
module.exports =
{ settings:
{ templateEngine: "twig"
}
}
Then the render function uses this engine under the hood to render the templates.
Note: Only Express compatible template engines are supported (which represents the large
majority of those available on npm).
templates/index.html (Twig example)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Users</title>
</head>
<body>
<ul>
{% for user in users %}
<li>{{ user.name }}</li>
{% endfor %}
</ul>
</body>
</html>
https://play.google.com/store/apps/details? Page: 33 / 37
www.BrainKart.
com
https://play.google.com/store/apps/details? Page: 34 / 37
www.BrainKart.
com
app.use(express.static('public'));
app.use(express.static('images'));
app.listen(3000);
Virtual Path Prefix
We can also provide a path prefix for serving static files. For example, if you want to provide
a path prefix like '/static', you need to include the following code in your index.js file −
var express =
require('express'); var app =
express();
app.use('/static',
express.static('public'));
app.listen(3000);
Now whenever you need to include a file, for example, a script file called main.js residing in
your public directory, use the following script tag −
<script src = "/static/main.js" />
This technique can come in handy when providing multiple directories as static files. These
prefixes can help distinguish between multiple directories.
https://play.google.com/store/apps/details? Page: 35 / 37
www.BrainKart.
com
Before Node version 7.6, the callbacks were the only official way provided by Node to run
one function after another. As Node architecture is single-threaded and asynchronous, the
community devised the callback functions, which would fire (or run) after the first function
(to which the callbacks were assigned) run is completed.
Example of a Callback:
app.get('/', function()
{ function1(arg1,
function(){
...
})
});
The problem with this kind of code is that this kind of situations can cause a lot of trouble
and the code can get messy when there are several functions. This situation is called what is
commonly known as a callback hell.
So, to find a way out, the idea of Promises and function chaining was introduced.
Example: Before async/await
function fun1(req, res){
return request.get('http://localhost:3000')
.catch((err)
=>{ console.log('found
error');
}).then((res) =>{
console.log('get request returned.');
});
Explanation:
The above code demos a function implemented with function chaining instead of callbacks. It
can be observed that the code is now more easy to understand and readable. The code
basically says that GET localhost:3000, catch the error if there is any; if there is no
error then implement the following statement:
console.log(‘get request returned.’);
With Node v8, the async/await feature was officially rolled out by the Node to deal with
Promises and function chaining. The functions need not to be chained one after another,
simply await the function that returns the Promise. But the function async needs to be
declared before awaiting a function returning a Promise. The code now looks like below.
Example: After async/await
async function fun1(req, res){
let response = await request.get('http://localhost:3000');
https://play.google.com/store/apps/details? Page: 36 / 37
www.BrainKart.
com
if (response.err) { console.log('error');}
else { console.log('fetched response');
}
Explanation:
The code above basically asks the javascript engine running the code to wait for
the request.get() function to complete before moving on to the next line to execute it.
The request.get() function returns a Promise for which user will await . Before async/await, if
it needs to be made sure that the functions are running in the desired sequence, that is one
after the another, chain them one after the another or register callbacks.
Code writing and understanding becomes easy with async/await as can be observed from
both the examples.
FETCHING JSON FROM EXPRESS
Write the ex: program 4 th and explain it.
https://play.google.com/store/apps/details? Page: 37 / 37
Click on Subject/Paper under Semester to
enter. Environmental
Professional English Sciences
Professional and Sustainability -
English - I - - II - HS3252 Discrete GE3451
HS3152 Mathematics -
Statistics and MA3354 Theory of
Numerical Computation
Matrices and
Methods - MA3251 Digital Principles
Calculus - CS3452
and Computer
- MA3151 Engineering Organization
Semester
Artificial
Semester
Semester
- CS3351
Semester
Graphics Intelligence and
Engineering Machine Learning
Physics - PH3151 - GE3251
Foundation of - CS3491
Data Science -
Physics for CS3352
2nd
Database Management
1st
Engineering Information
3rd
4th
Science System - CS3492
Chemistry
- PH3256 Data Structures and
- CY3151 Algorithms - CD3291
Web Essentials -
Basic Electrical and
Electronics IT3401
Problem Solving Engineering - BE3251 Object Oriented
and Python Programming - Introduction to
Programming - CS3391 Operating
Programming in C -
GE3151 Systems - CS3451
CS3251
Computer Networks
-
CS3591 Object Oriented
Software Human Values and
Full Stack Web Engineering - Ethics - GE3791
CCS356
Development -
Project Work /
Semester
Semester
Semester
Open Intership
Distributed Open Elective 3
Elective-1
Computing
Open Elective 4
7th
8th
- CS3551 Elective-3
5th
6th
Elective-4 Management
Embedded Systems
and IoT - CS3691
Elective-5 Elective
Elective 1
Elective-6
Elective 2
All Computer Engg [ B.E., M.E., ] (Click on Subjects to
Subjects - enter)
Programming in C Computer Operating Systems
Networks
Programming and Data Programming and Problem Solving and
Structures I Data Python
Structure II Programming
Database Management Computer Analog and Digital
Systems Architecture Communication
Design and Analysis of Microprocessors and Object Oriented
Algorithms Microcontrollers Analysis
and Design
Software Engineering Discrete Internet Programming
Mathematics
Theory of Computation Computer Graphics Distributed Systems
Mobile Computing Compiler Design Digital Signal
Processing
Artificial Intelligence Software Testing Grid and Cloud
Computing
Data Ware Housing and Cryptography and Resource
Data Mining Network Security Management
Techniques
Service Oriented Embedded and Real Multi - Core
Architecture Time Systems Architectures and
Programming
Probability and Queueing Physics for Transforms and
Theory Information Partial
Science Differential
Equations
Technical English Engineering Engineering Chemistry
Physics
Engineering Graphics Total Quality Professional Ethics in
Management Engineering
Basic Electrical and Problem Solving Environmental Science
Electronics and and Python and Engineering
Measurement Engineering Programming