Web Programming Technology
Web Programming Technology
EXPRESS JS……………………………………………………………………………………………………………………………………….16
ANGULAR…………………………………………………………………………………………………………………………………………24
NODEJS INTRODUCTION
Node.js is an open-source and cross-platform JavaScript runtime environment. It is a popular tool for
almost any kind of project!
Node.js runs the V8 JavaScript engine, the core of Google Chrome, outside of the browser. This
allows Node.js to be very performant.
A Node.js app is run in a single process, without creating a new thread for every request. Node.js
provides a set of asynchronous I/O primitives in its standard library that prevent JavaScript code
from blocking and generally, libraries in Node.js are written using non-blocking paradigms, making
blocking behavior the exception rather than the norm.
When Node.js performs an I/O operation, like reading from the network, accessing a database or the
filesystem, instead of blocking the thread and wasting CPU cycles waiting, Node.js will resume the
operations when the response comes back.
This allows Node.js to handle thousands of concurrent connections with a single server without
introducing the burden of managing thread concurrency, which could be a significant source of bugs.
Node.js has a unique advantage because millions of frontend developers that write JavaScript for the
browser are now able to write the server-side code in addition to the client-side code without the
need to learn a completely different language.
In Node.js the new ECMAScript standards can be used without problems, as you don't have to wait
for all your users to update their browsers - you are in charge of deciding which ECMAScript version
to use by changing the Node.js version, and you can also enable specific experimental features by
running Node.js with flags.
Many of those established over time as popular options. Here is a non-comprehensive list of the
ones worth learning:
AdonisJs: A full-stack framework highly focused on developer ergonomics, stability, and confidence.
Adonis is one of the fastest Node.js web frameworks.
Express: It provides one of the most simple yet powerful ways to create a web server. Its minimalist
approach, unopinionated, focused on the core features of a server, is key to its success.
Fastify: A web framework highly focused on providing the best developer experience with the least
overhead and a powerful plugin architecture. Fastify is one of the fastest Node.js web frameworks.
Gatsby: A React-based, GraphQL powered, static site generator with a very rich ecosystem of plugins
and starters.
hapi: A rich framework for building applications and services that enables developers to focus on
writing reusable application logic instead of spending time building infrastructure.
koa: It is built by the same team behind Express, aims to be even simpler and smaller, building on
top of years of knowledge. The new project born out of the need to create incompatible changes
without disrupting the existing community.
1
Loopback.io: Makes it easy to build modern applications that require complex integrations.
Meteor: An incredibly powerful full-stack framework, powering you with an isomorphic approach to
building apps with JavaScript, sharing code on the client and the server. Once an off-the-shelf tool
that provided everything, now integrates with frontend libs React, Vue, and Angular. Can be used to
create mobile apps as well.
Micro: It provides a very lightweight server to create asynchronous HTTP microservices.
NestJS: A TypeScript based progressive Node.js framework for building enterprise-grade efficient,
reliable and scalable server-side applications.
Next.js: A framework to render server-side rendered React applications.
Nx: A toolkit for full-stack monorepo development using NestJS, Express, React, Angular, and more!
Nx helps scale your development from one team building one application to many teams
collaborating on multiple applications!
Sapper: Sapper is a framework for building web applications of all sizes, with a beautiful
development experience and flexible filesystem-based routing. Offers SSR and more!
Socket.io: A real-time communication engine to build network applications.
Strapi: Strapi is a flexible, open-source Headless CMS that gives developers the freedom to choose
their favorite tools and frameworks while also allowing editors to easily manage and distribute their
content. By making the admin panel and API extensible through a plugin system, Strapi enables the
world's largest companies to accelerate content delivery while building beautiful digital experiences.
While learning to code, you might also be confused at where does JavaScript end, and where Node.js
begins, and vice versa.
I would recommend you to have a good grasp of the main JavaScript concepts before diving into
Node.js:
Lexical Structure
Expressions
Types
Variables
Functions
this
Arrow Functions
Loops
Scopes
Arrays
Template Literals
Semicolons
Strict Mode
ECMAScript 6, 2016, 2017
With those concepts in mind, you are well on your road to become a proficient JavaScript developer,
in both the browser and in Node.js.
2
The following concepts are also key to understand asynchronous programming, which is one
fundamental part of Node.js:
If your main Node.js application file is app.js, you can call it by typing:
node app.js
While running the command, make sure you are in the same directory which contains the app.js file.
In this file, functionality must be exposed before it can be imported by other files.
Any other object or variable defined in the file by default is private and not exposed to the outer
world.
This is what the module.exports API offered by the module system allows us to do.
When you assign an object or a function as a new exports property, that is the thing that's being
exposed, and as such, it can be imported in other parts of your app, or in other apps as well.
The first is to assign an object to module.exports, which is an object provided out of the box by the
module system, and this will make your file export just that object:
3
const car = {
brand: 'Ford',
model: 'Fiesta'
}
module.exports = car
const car = {
brand: 'Ford',
model: 'Fiesta'
}
exports.car = car
or directly
exports.car = {
brand: 'Ford',
model: 'Fiesta'
}
And in the other file, you'll use it by referencing a property of your import:
The first exposes the object it points to. The latter exposes the properties of the object it points to.
Introduction to npm
npm is the standard package manager for Node.js.
In January 2017 over 350000 packages were reported being listed in the npm registry, making it the
biggest single language code repository on Earth, and you can be sure there is a package for
(almost!) everything.
It started as a way to download and manage dependencies of Node.js packages, but it has since
become a tool used also in frontend JavaScript.
4
Yarn is an alternative to npm. Make sure you check it out as well.
Downloads
npm manages downloads of dependencies of your project.
npm install
it will install everything the project needs, in the node_modules folder, creating it if it's not existing
already.
--save installs and adds the entry to the package.json file dependencies
--save-dev installs and adds the entry to the package.json file devDependencies
The difference is mainly that devDependencies are usually development tools, like a testing library,
while dependencies are bundled with the app in production.
Updating packages
Updating is also made easy, by running
npm update
npm will check all packages for a newer version that satisfies your versioning constraints.
a local install
a global install
By default, when you type an npm install command, like:
As this happens, npm also adds the lodash entry in the dependencies property of the package.json
file present in the current folder.
5
A global installation is performed using the -g flag:
Where, exactly?
The npm root -g command will tell you where that exact location is on your machine.
If you use nvm to manage Node.js versions, however, that location would differ.
When you install using npm a package into your node_modules folder, or also globally, how do
you use it in your Node.js code?
Say you install lodash, the popular JavaScript utility library, using
To use it in your code, you just need to import it into your program using require:
const _ = require('lodash')
To see the latest version of all installed npm packages, including their dependencies:
npm list
6
What is Node js Module?
Module in Node.js is a simple or complex functionality organized in single or multiple JavaScript files
which can be reused throughout the Node.js application.
Each module in Node.js has its own context, so it cannot interfere with other modules or pollute
global scope.
Also, each module can be placed in a separate .js file under a separate folder.
There are different Node.js Module Types.
Core Modules
Local Modules
Core Modules
The core modules are built in modules .These core modules are compiled into its binary distribution
and load automatically when Node.js process starts.
The following table lists some of the important core modules in Node.js.
Name Description
http http module includes classes, methods and events to create Node.js http server.
url url module includes methods for URL resolution and parsing
Fs fs module includes classes, methods, and events to work with file I/O.
Local Modules
Local modules are modules created locally in your Node.js application.
These modules include different functionalities of your application in separate files and folders.
You can also package it and distribute it via NPM, so that Node.js community can use it.
In Node.js, module should be placed in a separate JavaScript file.
At the end, we have assigned this object to module.exports.
The module.exports in the above example exposes a log object as a module.
7
Sample Program app.js
const readline = require('readline').createInterface({
input: process.stdin,
output: process.stdout
})
Node.js since version 7 provides the readline module to perform exactly this: get input from a
readable stream such as the process.
stdin stream, which during the execution of a Node.js program is the terminal input, one line at a
time.
This piece of code asks the username, and once the text is entered and the user presses enter, we
send a greeting.
The question() method shows the first parameter (a question) and waits for the user input. It calls
the callback function once enter is pressed.
8
Loading arithmetic module in app.js
const arithmetic=require('./arithmetic');
var res=arithmetic.add(10,20);
console.log("The addition is "+res);
var fact_res=arithmetic.factorial(4);
console.log(fact_res);
9
‘fs’ module
The fs module provides an API for interacting with the file system in a manner closely modeled
around standard POSIX functions.
All file system operations have synchronous and asynchronous forms.
The asynchronous form always takes a completion callback as its last argument.
In busy processes, use the asynchronous versions of these calls. The synchronous versions will block
the entire process until they complete, halting all connections.
Create one text file SAMPLE.TXT with some content into it.
Demo for reading file synchronously in app.js
var fs=require('fs');
data=fs.readFileSync("SAMPLE.txt");
console.log(data.toString());
console.log("Reading data completed");
var fs=require("fs");
fs.readFile("SAMPLE.txt",function(error,data){
if(error){
console.log("error occured");
}else{
console.log(data.toString());
console.log("Reading Data completed here");
}
10
});
console.log("Reading Data completed here");
fs.stat("SAMPLE.txt",function(error,stats){
if(error){
console.log("error in stat");
}
else{
console.log(stats);
}
});
console.log("Readign program stat ends here");
Demo for writing data into text file Asynchronously in app.js program
fs = require('fs')
11
‘http’ Module
To use the HTTP server and client one must require('http').
The HTTP interfaces in Node.js are designed to support many features of the protocol which have
been traditionally difficult to use.
http.createserver() returns a new instance of http.Server.
server.listen() method creates a listener on the specified port or path.
When an HTTP request hits the server, node calls the request handler function with a few handy
objects for dealing with the transaction, request and response.
};
serv=http.createServer(processrequest);
serv.listen(3000);
console.log("Your computer is a server running at port 3000");
Run the above program and make a request from browser to http://localhost:3000
‘url’ Module
url is a module that helps us to deal with url.
The URL module splits up a web address into readable parts.
Parse an address with the url.parse() method, and it will return a URL object with each part of the
address as properties like host,pathname,search.
Demo app.js for using url module for reading the different url paths requested and accordingly
sending back different responses
http=require("http");
url=require("url");
processdata=function(req,resp){
d=url.parse(req.url);
console.log(d);
switch(d.pathname){
case "/":
resp.writeHead(200,{'Content-Type':'text/html'});
resp.end("<h1>You are on Home page</h1>");
break;
case "/about":
resp.writeHead(200,{'Content-Type':'text/html'});
resp.end("<h1>a You are on About us Page</h1>");
break;
default:
resp.writeHead(200,{'Content-Type':'text/html'});
resp.end("<h1>page not found</h1>");
break;
12
}
}
http.createServer(processdata).listen(3000);
console.log("server is running at 3000");
Run the above program and make a request from browser to http://localhost:3000 and see the
response. Also observe the response for http://localhost:3000/about and
http://localhost:3000/contactus
'querystring' module
The querystring module provides utilities for parsing and formatting URL query strings.
It can be accessed using:
const querystring = require('querystring');
The querystring.parse() method parses a URL query string (str) into a collection of key and value
pairs.
Demo App.js for using querystring module for fetching username and password for validating the
user and sending back response accordingly.
Step1: create a module loginmodule.js
var loginUser= {
validate:function(name,password) {
if(name=="ashwini" && password=="123")
{
return true;
}
return false;
}
}
module.exports=loginUser;
fs=require('fs')
http=require("http");
url=require("url");
query=require("querystring");
loginUser=require("./loginmodule1");
processdata=function(req,resp){
reqUrl=url.parse(req.url);
console.log(reqUrl);
switch(reqUrl.pathname){
case "/":
resp.writeHead(200,{'Content-Type':'text/html'})
fs.readFile("Welcome.html",function(error,data){
if(error){
13
console.log("error ocureed");
}
else{
resp.end(data);
}
});
break;
case "/validate":
resp.writeHead(200,{'Content-Type':'text/html'})
data=query.parse(reqUrl.query);
if(loginUser.validate(data.username,data.password)==true)
{
resp.end("Login successfull. Welcome to your page");
}
else
{
resp.end("Invalid credentials!!!");
}
break;
default:
resp.writeHead(200,{'Content-Type':'text/html'})
resp.end("<h1>page not found</h1>");
break;
}
}
http.createServer(processdata).listen(3000);
console.log("server is running at 3000");
<div class="container">
<h2>Form control: input</h2>
<p>The form below contains two input elements; one of type text and one of type
password:</p>
<form action="/validate">
14
<div class="form-group">
<label for="usr">Name:</label>
<input type="text" class="form-control" id="usr" name="username">
</div>
<div class="form-group">
<label for="pwd">Password:</label>
<input type="password" class="form-control" id="pwd" name="password">
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
</div>
</body>
</html>
Run app.js and see the output in browser for this url http://localhost:3000
15
ExpressJS
Express is a minimal and flexible Node.js web application framework that provides a robust set of
features for web and mobile applications.
You can assume express as a layer built on the top of the Node.js that helps manage a server and
routes.
It can be used to design single-page, multi-page and hybrid web applications.
It allows to setup middlewares to respond to HTTP Requests.
It defines a routing table which is used to perform different actions based on HTTP method and URL.
Installation of express
You have to install the express framework globally to create web application using Node terminal.
Use the following command to install express framework globally.
npm install -g express
16
Demo app.js for using express framework
var express = require('express');
var app = express();
app.get("/",function(req,resp){
resp.send("<h1>Hello world!! you requested "+ req.path+"</h1>");
});
app.get("/about",function(req,resp){
resp.send("<h1>about us !!! you requested "+ req.path+"</h1>");
});
app.listen(3000,function(){
console.log("server listening on port 3000");
});
app.get("/",function(req,resp){
17
resp.send("<h1>Hello world!!</h1>");
});
app.get("/about",function(req,resp){
resp.send("<h1>about us</h1>");
});
Routing
Routing is made from the word route. It is used to determine the specific behavior of an application.
It specifies how an application responds to a client request to a particular route, URI or path and a
specific HTTP request method (GET, POST, etc.).
It can handle different types of HTTP requests.
Body-parser module
body-parser extract the entire body portion of an incoming request stream and exposes it on
req.body.
The middleware was a part of Express.js earlier but now you have to install it separately.
This body-parser module parses the JSON, buffer, string and URL encoded data submitted using
HTTP POST request. Install body-parser using NPM as shown below.
npm install body-parser –save
Demo for observing body-parser module and routing of get as well as post requests using expressjs
Step1- create registration.html
<!DOCTYPE html>
<html>
<body>
<form action="/register" method="post">
<table>
<tr><td>Enter First Name:</td><td><input type="text" name="firstname"/><td></tr>
<tr><td>Enter Last Name:</td><td><input type="text" name="lastname"/><td></tr>
<tr><td>Enter Password:</td><td><input type="password" name="password"/></td></tr>
<tr><td>Sex:</td><td>
<input type="radio" name="gender" value="male"> Male
<input type="radio" name="gender" value="female">Female
</td></tr>
<tr><td>About You :</td><td>
<textarea rows="5" cols="40" name="aboutyou" placeholder="Write about yourself">
</textarea>
</td></tr>
<tr><td colspan="2"><input type="submit" value="register"/></td></tr>
</table>
</form>
</body>
</html>
18
bodyparser=require("body-parser");
app.use(bodyparser.urlencoded({extended:false}));
app.use(function(req,resp,next){
console.log("url:"+req.url)
next();
});
app.use(function(req,resp,next){
console.log("Method:"+req.method)
next();
});
app.get('/',function(req,res){
res.sendFile(__dirname+'/registration.html')
})
<div class="container">
<h2>Login</h2>
19
</div>
<div class="form-group">
<label for="pwd">Password:</label>
<input type="password" class="form-control" id="pwd" name="password">
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
</div>
</body>
</html>
validate:function(name,password) {
if(name=="ashwini" && password=="123")
{
return true;
}
return false;
}
}
module.exports=loginUser;
express=require('express');
app=express();
bodyParser=require('body-parser');
app.use(bodyParser.urlencoded({extended:false}));
app.use(bodyParser.json());
app.get('/',function(req,res){
res.sendFile(__dirname+'/Login.html');
})
app.post("/validate",function(req,res){
username=req.body.username;
password=req.body.password;
console.log("username="+username+" password="+password);
if(loginUser.validate(username,password)==true)
{
res.send("<form action=\"/continue\" method=\"post\">"+
"<h1> Hi "+username+", welcome to online shop</h1>"+
"<input type=\"submit\" value=\"submit\"/>");
20
}
else{
res.sendFile(__dirname+'/Login.html');
}
})
app.post("/continue",function(req,res)
{
res.send("Hi "+req.body.username +" you are on continue page");
})
server=app.listen(3000,function(){
console.log("server listening at port 3000");
})
<div class="container">
<h2>Login</h2>
21
<form action="/validate" method="POST">
<div class="form-group">
<label for="usr">Name:</label>
<input type="text" class="form-control" id="usr" name="username">
</div>
<div class="form-group">
<label for="pwd">Password:</label>
<input type="password" class="form-control" id="pwd" name="password">
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
</div>
</body>
</html>
validate:function(name,password) {
if(name=="ashwini" && password=="123")
{
return true;
}
return false;
}
}
module.exports=loginUser;
Step3- app.js
loginUser=require('./loginmodule');
express=require('express');
app=express();
cookieparser=require('cookie-parser');
bodyParser=require('body-parser');
app.use(bodyParser.urlencoded({extended:false}));
app.use(bodyParser.json());
app.use(cookieparser());
app.get('/',function(req,res){
res.sendFile(__dirname+'/Login.html');
})
app.post("/validate",function(req,res){
22
username=req.body.username;
password=req.body.password;
console.log("username="+username+" password="+password);
if(loginUser.validate(username,password)==true)
{
let userinfo={"uname":username};
res.cookie("userinfo",userinfo,{maxAge:4000});
res.send("<form action=\"/continue\" method=\"post\">"+
"<h1> Hi "+username+", welcome to online shop</h1>"+
"<input type=\"submit\" value=\"submit\"/>");
}
else{
res.sendFile(__dirname+'/Login.html');
}
})
app.post("/continue",function(req,res)
{
if(req.cookies.userinfo=="undefined")
{
console.log("The cookie is "+req.cookies.userinfo["uname"].toString());
res.send("Hi "+req.cookies.userinfo["uname"] +" you are on continue page");
}
else
{
res.send("<h1>session expired. login again</h1>");
}
})
server=app.listen(3000,function(){
console.log("server listening at port 3000");
})
23
Introduction to Angular
Angular is an application design framework and development platform for creating efficient and
sophisticated single-page apps.
To install Angular on your local system, you need the following:
Node.js
npm package manager
Angular, the Angular CLI, and Angular applications depend on npm packages for many features and
functions. To download and install npm packages, you need an npm package manager.
To install the Angular CLI, open a terminal window and run the following command:
npm install -g @angular/cli
24
Angular Components Overview
Components are the main building block for Angular applications. Each component consists of:
An HTML template that declares what renders on the page
A Typescript class that defines behavior
A CSS selector that defines how the component is used in a template
Optionally, CSS styles applied to the template
@Component({
})
Choose a CSS selector for the component.
@Component({
selector: 'app-component-overview',
})
For more information on choosing a selector, see Specifying a component's selector.
25
Define the HTML template that the component uses to display information. In most cases, this
template is a separate HTML file.
@Component({
selector: 'app-component-overview',
templateUrl: './component-overview.component.html',
})
For more information on defining a component's template, see Defining a component's template.
Select the styles for the component's template. In most cases, you define the styles for you
component's template in a separate file.
@Component({
selector: 'app-component-overview',
templateUrl: './component-overview.component.html',
styleUrls: ['./component-overview.component.css']
})
Add a class statement that includes the code for the component.
}
Specifying a component's CSS selector
Every component requires a CSS selector. A selector instructs Angular to instantiate this component
wherever it finds the corresponding tag in template HTML. For example, consider a component,
hello-world.component.ts that defines its selector as app-hello-world. This selector instructs angular
to instantiate this component any time the tag, <app-hellow-world> in a template.
@Component({
selector: 'app-component-overview',
})
Defining a component's template
A template is a block of HTML that tells Angular how to render the component in your application.
You can define a template for your component in one of two ways: by referencing an external file, or
directly within the component.
To define a template as an external file, add a templateUrl property to the @Component decorator.
@Component({
selector: 'app-component-overview',
templateUrl: './component-overview.component.html',
})
To define a template within the component, add a template property to the @Component decorator
that contains the HTML you want to use.
26
@Component({
selector: 'app-component-overview',
template: '<h1>Hello World!</h1>',
})
If your want your template to span multiple lines, you can use backticks ( ` ). For example:
@Component({
selector: 'app-component-overview',
template: `<h1>Hello World!</h1>
<p>This template definition spans
multiple lines.</p>`
})
An Angular component requires a template defined using template or templateUrl. You cannot have
both statements in a component.
To declare the styles for a component in a separate file, add a stylesUrls property to the
@Component decorator.
@Component({
selector: 'app-component-overview',
templateUrl: './component-overview.component.html',
styleUrls: ['./component-overview.component.css']
})
To select the styles within the component, add a styles property to the @Component decorator that
contains the styles you want to use.
@Component({
selector: 'app-component-overview',
template: '<h1>Hello World!</h1>',
styles: ['h1 { font-weight: normal; }']
})
The styles property takes an array of strings that contain the CSS rule declarations.
Templates
Each Angular template in your app is a section of HTML that you can include as a part of the page
that the browser displays. An Angular HTML template renders a view, or user interface, in the
browser, just like regular HTML, but with a lot more functionality.
When you generate an Angular app with the Angular CLI, the app.component.html file is the default
template containing placeholder HTML.
With special Angular syntax in your templates, you can extend the HTML vocabulary of your apps.
For example, Angular helps you get and set DOM (Document Object Model) values dynamically with
features such as built-in template functions, variables, event listening, and data binding.
27
Interpolation and template expressions
Interpolation allows you to incorporate calculated strings into the text between HTML element tags
and within attribute assignments. Template expressions are what you use to calculate those strings.
Interpolation {{...}}
Interpolation refers to embedding expressions into marked up text. By default, interpolation uses as
its delimiter the double curly braces, {{ and }}.
28