Unit II - Server Side Programming With Node JS
Unit II - Server Side Programming With Node JS
Agenda
Introduction
• A web server is a software or hardware system that processes requests and delivers web pages to
users over the Internet or a private network. It serves HTML pages, images, videos, and other
web content to browsers via HTTP (Hypertext Transfer Protocol) or HTTPS (secure version of
HTTP).
• A computer program that accepts HTTP requests and returns HTTP responses with optional data
content.
• A Web server typically serves static content residing on a file system (HTML Pages, images,
audio and video files).
• Web servers route requests for dynamic content (Non-Web Content) using “Web Gateways”.
5 MCA4201- FULL STACK WEB DEVELOPMENT | © SmartCliff | Internal | Version 1.2
Introduction to web servers
• When client sends request for a web page, the web server search for the requested page if
requested page is found then it will send it to client with an HTTP response.
• If the requested web page is not found, web server will the send an HTTP response: Error 404 Not
found.
• If client has requested for some other resources then the web server will contact to the application
Examples of webservers
• This is the most popular web server in the world developed by the Apache Software Foundation.
• Apache web server is an open source software and can be installed on almost all operating systems
including Linux, UNIX, Windows, FreeBSD, Mac OS X and more. About 60% of the web server
Examples of webservers
• The Internet Information Server (IIS) is a high performance Web Server from Microsoft. This web
server runs on Windows NT/2000 and 2003 platforms (and may be on upcoming new Windows
version also).
• IIS comes bundled with Windows NT/2000 and 2003; Because IIS is tightly integrated with the
Examples of webservers
• This web server from Sun Microsystems is suited for medium and large web sites.
• It however, runs on Windows, Linux and UNIX platforms. The Sun Java System web server supports
various languages, scripts and technologies required for Web 2.0 such as JSP, Java Servlets, PHP,
Architecture
• kindly refer the content--- “Computer Network basics-> Web System Architecture”
• It provides an event driven, non-blocking (asynchronous) I/O and cross-platform runtime environment
• It provides a rich library of various JavaScript modules which simplifies the development of
web applications using Node.js to a great extent.
Node JS
Build-in Modules
JavaScript
JavaScript on the Server
V8 Engine API
V8 Engine
Running on Node.js
• Chrome's V8 JavaScript engine was used by JavaScript to execute the code in browser.
• Node JS also used Chrome's V8 JavaScript engine to execute the code on server-side.
• In client side we can run HTML, CSS and JavaScript with the help of using browser.
• We can also run the JavaScript code in server side with the help of Node JS. Here we no need of
browser to run the JavaScript code, We can run our JavaScript code in Node JS with the help of PC
itself.
• Node. JS is not a programming language. Rather, it's a runtime environment that's used to run JavaScript
• Is Node JS is a Framework?
• Node JS is not a framework, but It is used to build scalable network applications using an event-driven,
non-blocking I/O model, which makes it fast and light on resources. It allows developers to use a single
• A runtime environment (RTE) is a collection of web APIs that a developer can use to create a code and a
• We write the built-in modules code through JavaScript code and run it on Node JS v8 engine. During
runtime the Node JS will call the modules through API and produce the output.
– If no thread is available in the thread pool at any point of time then the request waits till the next
available thread.
– Dedicated thread executes a particular request and does not return to thread pool until it completes the
execution and returns a response.
• Node.js processes user requests differently when compared to a traditional web server model.
• Node.js runs in a single process and the application code runs in a single thread
• All the user requests to web application will be handled by a single thread and all the I/O work or long
running job is performed asynchronously for a particular request.
– So, this single thread doesn't have to wait for the request to complete and is free to handle the next
request.
– When asynchronous I/O work completes then it processes the request further and sends the response.
• An event loop is constantly watching for the events to be raised for an asynchronous job and executing
callback function when the job completes.
Features of Node.js
– It essentially means a Node.js based server never waits for an API to return data. The server moves to
– A notification mechanism of Events of Node.js helps the server to get a response from the previous API
call.
• Very Fast
− Being built on Google Chrome's V8 JavaScript Engine, Node.js library is very fast in code execution.
Features of Node.js
– Event mechanism helps the server to respond in a non-blocking way and makes the server highly
scalable as opposed to traditional servers which create limited threads to handle requests.
– Node.js uses a single threaded program and the same program can provide service to a much larger
• No Buffering
− Node.js applications never buffer any data. These applications simply output the data in chunks.
Advantages of Node.js
• Node.js offers an Easy Scalability
• Easy to Learn
• High Performance
• Advantage of Caching
• Highly Extensible
23 Node.js | © Smartcliff | Internal | Version 1.0
Javascript in the Desktop with NodeJS
Applications of Node.js
• Node.js can be used efficiently in many kinds of applications.
– IoT applications
– real-time chats,
– streaming apps
• A large number of corporate giants have adopted Node.js application development like PayPal,
LinkedIn, Netflix, Uber, GoDaddy, eBay, and so on.
Environment Setup
• Node.js development environment can be setup in Windows, Mac, Linux and Solaris.
• The following tools/SDK are required for developing a Node.js application on any platform,
1. Node.js
– It will automatically detect OS and display download link as per your Operating System.
– Once the Node.js installed , can verify it by opening the command prompt and typing node -v.
– If Node.js is installed successfully then it will display the version of the Node.js
Node.js Console/REPL
• Node.js comes with virtual environment called REPL (i.e Node shell).
– type node
Node.js Console/REPL
Simple Expression
Node.js Console/REPL
Use Variables
• We can make use of variables to store values and print later like any conventional script.
– If var keyword is not used, then the value is stored in the variable and printed.
– If var keyword is used, then the value is stored but not printed.
Node.js Console/REPL
Multiline Expression
Node.js Console/REPL
To execute an external JavaScript file
• For example, the following runs mynodejs-app.js on the command prompt/terminal and displays the
result.
Command prompt
Node.js Console/REPL
Stopping REPL
• To exit from the REPL terminal, press Ctrl + C twice or write .exit and press Enter.
Node.js Console/REPL
REPL Commands
REPL Command Description
ctrl + c Terminate the current command.
ctrl + c (twice) Exit from the REPL.
ctrl + d Exit from the REPL.
.break Exit from multiline expression.
.clear Exit from multiline expression.
.help Display help on all the commands
tab Keys Display the list of all commands.
Up/Down Keys See previous commands applied in REPL.
.load filename Load the specified file in the current Node REPL
session.
32 Node.js | © Smartcliff | Internal | Version 1.0
Javascript in the Desktop with NodeJS
Node.js Fundamentals
• Node.js supports JavaScript.
• Primitive Types
– String
– Number
– Boolean
– Undefined
– Null
– RegExp
Node.js Fundamentals
• Loose Typing
• Object Literal
var obj = {
authorName: 'Ryan Dahl',
language: 'Node.js'
}
Node.js Fundamentals
• Functions
– Functions are first class citizens in Node's JavaScript, similar to the browser's JavaScript.
Filename: app.js
function Display(x) {
console.log(x);
}
Display(100);
Node.js Fundamentals
• Arrow Functions
–
Filename: functiondemo.js
function sum(a,b) {
return a+b;
}
var s = sum(3,4);
console.log("Normal Function: " + s);
• Node's JavaScript is different from browser's JavaScript when it comes to global scope.
Installing NPM:
To install NPM, it is required to install Node.js as NPM gets installed with Node.js automatically.
npm –v
• Older version of NPM can be updated to the latest version using the following command.
"name": "notes-app",
• To create a Node project, npm init is used in the folder
"version": "1.0.0",
in which user want to create project.
"description": "",
• The npm command line will ask a number of questions "main": "app.js",
"scripts": {
like name, license, scripts, description, author,
"test": "echo \"Error: no test specified\"
keywords, version, main file etc.
&& exit 1"
"author": "",
a package.json file will be visible in project folder as a
"license": "ISC",
proof that the project has been initialized.
}
40 Node.js | © Smartcliff | Internal | Version 1.0
Node Package Manager(NPM)
• After creating the project, next step is to incorporate the packages and modules to be used in the Node
Project.
• To install packages and modules in the project (locally) the following syntax:
• NPM can also install packages globally so that all the node.js application on that computer can import
and use the installed packages.
– npm uses this directory to store all the code for the npm modules that have installed.
• Second, npm adds the module as a dependency by listing it in the dependencies property in package.json.
– This allows to track and manage the module that have installed.
– This includes detailed information about the modules that have installed which helps keep things fast
and secure
• To install a package and simultaneously save it in package.json file (in case using Node.js), add –
save flag.
• The –save flag is default in npm install command so it is equal to npm install package_name command.
• npm modules can be imported into your script using require() function.
Filename: validator.js
The script then uses the isURL() function provided by validator to check if a given string contains a
valid URL.
Update Package:
Uninstalling Packages:
• nodemon is a tool that helps develop node.js based applications by automatically restarting the node
• nodemon does not require any additional changes to the code or method of development.
• To use nodemon, replace the word node on the command line when executing the script.
• Installation: nodemon will be installed globally to our system path using below syntax:
• Usage : nodemon wraps the application, so that we can pass all the arguments we would normally
pass to our app:
Filename: index.js
const http = require("http");
const server = http.createServer((req,res) => {
res.writeHead(200, {'Content-Type': 'text/html'});
res.write('Welcome to Node.js!');
res.end();
});
server.listen(3000);
While nodemon is still running, let’s make a change to the index.js file.
Add a message: ‘Node.js is an open-source server side runtime environment.’.
• The terminal output from the Node.js app is displaying the new changes.
• We can restart the process at any time by typing rs and hitting ENTER.
• Alternatively, nodemon will also look for a main file specified in our project’s package.json file:
Filename: package.json
{
// ...
"main": “index.js",
// ...
}
• If a main file is not specified, nodemon will search for a start script:
Filename: package.json
{
// ...
"scripts": {
"start": "node index.js"
},
// ...
}
• Once we make the changes to package.json, we can then call nodemon to start the example app in
– The task of a web server is to open a file on the server and return the content to the client.
• The web server will handle all the http requests for the web application
– e.g IIS is a web server for ASP.NET web applications and Apache is a web server for PHP or Java web
applications.
• Node.js provides capabilities to create our own web server which will handle HTTP requests
asynchronously.
• We can use IIS or Apache to run Node.js web application but it is recommended to use Node.js web
server.
55 Node.js | © Smartcliff | Internal | Version 1.0
NodeJS Web Server
• Node.js makes it easy to create a simple web server that processes incoming requests
asynchronously.
• Node.js has a built-in module called HTTP, which allows Node.js to transfer data over the Hyper Text
• The HTTP module can create an HTTP server that listens to server ports and gives a response back to
the client.
Filename: http_server.js
});
• The http module is a core module of Node.js, so no need to install it using NPM.
• The next step is to call createServer() method of http and specify callback function with request
and response parameter.
• Finally, call listen() method of server object which was returned from createServer() method with port
number, to start listening to incoming requests on port 3000.
• The http.createServer() method includes request and response parameters which is supplied by
Node.js.
• The request object can be used to get information about the current HTTP request e.g., url, request
• The response object can be used to send a response for a current HTTP request.
• req.url is used to check the url of the current request and based on that it sends the response.
• To send a response, first it sets the response header using writeHead() method and then writes a
• Finally, Node.js web server sends the response using end() method.
• Point the browser to http://localhost:3000 and see the Node.js Web Server Response.
• Point the browser to http://localhost:3000/data and see the Node.js Web Server Response.
Node Framework
• A framework is a collection of various libraries and tools that are required in the development
• A node framework is a workspace platform that supports the use of Node.js and which allows
developers to use JavaScript for developing front end as well as the back end of an application.
• Node frameworks are a wide collection of frameworks built on Node and that extend its properties
Node Framework
• Productivity
• Scalability
• Speed
• There are various third party open-source frameworks available in Node Package Manager which
makes Node.js application development faster and easy.
Open-Source
Framework Description
Express.js Express is a minimal and flexible Node.js web application framework that provides a
robust set of features for web and mobile applications. This is the most popular
framework as of now for Node.js.
Geddy Geddy is a simple, structured web application framework for Node.js based on MVC
architecture.
Hapi.js Hapi is a rich Node.js framework for building applications and services.
71 Node.js | © Smartcliff | Internal | Version 1.0
Frameworks for NodeJS
Total.js Totaljs is free web application framework for building web sites and web applications
using JavaScript, HTML and CSS on Node.js
Keystone Keystone is the open source framework for developing database-driven websites,
applications and APIs in Node.js. Built on Express and MongoDB.
72 Node.js | © Smartcliff | Internal | Version 1.0
Frameworks for NodeJS
Mojito This HTML5 framework for the browser and server from Yahoo offers direct MVC access
to the server database through the local routines. One clever feature allows the code to
migrate. If the client can't run JavaScript for some reason, Mojito will run it on the server -
- a convenient way to handle very thin clients.
Restify Restify is a node.js module built specifically to enable you to build correct REST web
services.
Frisby Frisby is a REST API testing framework built on node.js and Jasmine that makes testing
API endpoints easy, fast, and fun.
Chocolate.js Chocolate is a simple webapp framework built on Node.js using Coffeescript.
Mean.js It is an added Node.js framework mounted on the top of Express. It helps you create
secure, robust, and maintainable production web applications using MongoDB,
Express, AngularJS, and Node.js.
NestJS It is a Node.js framework used for building server-side applications that are efficient in
every way. Apart from using JavaScript, it also supports TypeScript along with certain
elements of Functional Programming (FP), Object-Oriented Programming (OOP) and
Function Reactive Programming (FRP).
AdonisJS It is a Node.js MVC framework that provides the ability to write web applications by
using less code and focuses on being a stable framework in the colony of Node
frameworks. One important factor about AdonisJS is that it contains a number of test
modules that help to improve the efficiency of one’s code.
• Express was developed by TJ Holowaychuk and is maintained by the Node.js foundation and
• It provides various features that make web application development fast and easy which otherwise takes
• It is specifically designed for building single-page, multi-page, and hybrid web applications.
• The Express.js framework makes it very easy to develop an application which can be used to handle
multiple types of requests like the GET, PUT, and POST and DELETE requests.
• Express.js is based on the Node.js middleware module called connect which in turn uses http module.
• So, any middleware which is based on connect will also work with Express.js.
Express.js
connect
http
Node.js
Advantages of Express.js
• Allows to define routes of your application based on HTTP methods and URLs.
• Includes various middleware modules which can use to perform additional tasks on request and
response.
• Easy to integrate with different template engines like Jade, Vash, EJS etc.
Install Express.js
• The following command will install latest version of express.js local to the project folder.
Install Express.js
• Figure shows express is added under dependencies section,
• Note: use “npm uninstall express” will remove express and updates in package.json file.
Install Express.js
• To make our development process a lot easier, we will install a tool from npm, nodemon.
• This tool restarts our server as soon as we make a change in any of our files, otherwise we need to
restart the server manually after each file modification.
• To install nodemon, use the following command −
• Lets create a file called app.js and type the following in it.
Filename: app.js
const express = require('express’); //imported Express.js module using require()
function
const app = express();
const PORT = 3000;
app.listen(PORT, () => {
console.log(`Server is listening at http://localhost:${PORT}`);
});
• This will start the server. To test this app, open the browser and go to http://localhost:3000 and a
message will be displayed as in the following screenshot.
• The first line imports Express in our file, we have access to it through the variable ‘express’.
• app.get(route, callback) function tells what to do when a get request at the given route is called.
– The request object(req) represents the HTTP request and has properties for the request query string,
– Similarly, the response object represents the HTTP response that the Express app sends when it
receives an HTTP request.
• res.send() function takes an object as input and it sends this to the requesting client. Here we are
• app.listen(port, [host], [backlog], [callback]]) function binds and listens for connections on the
specified host and port. Port is the only required parameter here.
Routing
• Routing refers to determining how an application responds to a client request to a particular endpoint,
which is a URI (or path) and a specific HTTP request method (GET, POST, and so on).
• Each route can have one or more handler functions, which are executed when the route is matched.
– HANDLER is the callback function that is executed when the matching request type is found on the relevant
route.
HTTP Methods
The HTTP method is supplied in the request and specifies the operation that the client has
requested. The following table lists the most used HTTP methods −
Method Description
GET The GET method requests a representation of the specified resource. Requests
using GET should only retrieve data and should have no other effect.
POST The POST method requests that the server accept the data enclosed in the
request as a new object/entity of the resource identified by the URI.
PUT The PUT method requests that the server accept the data enclosed in the request
as a modification to existing object identified by the URI.
If it does not exist then the PUT method should create one.
DELETE The DELETE method requests that the server delete the specified resource.
Filename: get_route.js
var express = require('express');
var app = express();
app.get('/hello', function(req, res){
res.send("Hello World!");
});
app.listen(3000);
Routing - Example
• If we run our application and go to localhost:3000/hello, the server receives a get request at
route "/hello", our Express app executes the callback function attached to this route and
sends "Hello World!" as the response.
• It has a callback function (req, res) that listen to the incoming request req object and respond
accordingly using res response object.
• Both req and res are made available to us by the Express framework.
• The req object represents the HTTP request and has properties for the request query string,
parameters, body, and HTTP headers.
• The res object represents the HTTP response that an Express app sends when it gets an HTTP
request.
• In our case, we are sending a text Hello World whenever a request is made to the route /.
• Lastly, app.listen() is the function that starts a port and host, in our case the localhost for the connections
to listen to incoming requests from a client. We can define the port number such as 3000.
93 Express.js | © Smartcliff | Internal | Version 1.0
Routing and HTTP Methods
• For understanding purpose, let’s see Facebook profile link https://fb.com/itsaareez1 where ‘itsaareez1’ is
profile’s username.
• Every user has a unique username so, this value will vary according to user. This is dynamic routing.
Filename: dynamic_route.js
var express = require('express');
var app = express();
• Example
Filename: dynamic_route2.js
var express = require('express');
var app = express();
We can use the req.params object to access all the parameters you pass in the url. Note that the above 2
are different paths. They will never overlap. Also if you want to execute code when you get '/things' then
you need to define it separately.
Configure Routes
• A special method, all, is provided by Express to handle all types of http methods at a particular route
• Like if we have POST, GET, PUT, DELETE, etc, request made to any specific route, let say /user, so
instead to defining different API’s like app.post(‘/user’), app.get(‘/user’), etc, we can define single
Configure Routes
Filename: app.js
var express = require('express');
var app = express();
var PORT = 3000;
app.all('/user', function (req, res) {
console.log('USER API CALLED');
res.send('<html><body><h1>Hello World</h1></body></html>');
});
app.listen(PORT, function(){
console.log("Server listening on PORT", PORT);
});
Configure Routes
• Run the command nodemon app.js and point the browser to http://localhost:3000 and see the following
result.
Route parameters
• Route parameters are named URL segments that are used to capture the values specified at their position in
the URL. The name of route parameters must be made up of “word characters” ([A-Za-z0-9_]).
• The captured values are populated in the req.params object, with the name of the route parameter specified in
the path as their respective keys.
• To define routes with route parameters, simply specify the route parameters in the path of the route:
Route parameters
• Since the hyphen (-) and the dot (.) are interpreted literally, they can be used along with route parameters
for useful purposes.
Route parameters
• To have more control over the exact string that can be matched by a route parameter, we can append a
regular expression in parentheses (()):
• Because the regular expression is usually part of a literal string, be sure to escape any \ characters with
an additional backslash, for example \\d+.
Route parameters
Filename: route-params.js
var express = require('express');
var app = express();
app.get('/user/:userId/books/:bookid', (req, res) => {
req.params; // { userId: '42' }
res.json(req.params);
});
app.get('/flights/:from-:to', (req, res) => {
req.params; // { "from": "LAX", "to": "SFO" }
res.json(req.params);
});
Route parameters
app.get('/plantae/:genus.:species', (req, res) => {
req.params; // { "genus": "Prunus", "species": "persica" }
res.json(req.params);
});
app.get('/user/:userId', (req, res) => {
req.params; // {"userId": "42"}
res.json(req.params);
});
var server = app.listen(3000, function () {
console.log('Node server is running..');
});
• First, create index.html file in the root folder of your application and write the following HTML code in it.
Filename: index.html
<!DOCTYPE html>
<html >
<head>
<meta charset="utf-8" />
<title></title>
</head>
<body>
<form action="/submit-data" method="post">
First Name: <input name="firstName" type="text" /> <br />
Last Name: <input name="lastName" type="text" /> <br />
<input type="submit" /> </form> </body> </html>
108 Express.js | © Smartcliff | Internal | Version 1.0
Routing and HTTP Methods
Body Parser
• To handle HTTP POST request in Express.js version 4 and above, we need to install middleware module
called body-parser.
• The middleware was a part of Express.js earlier but now we have to install it separately.
• This body-parser module parses the JSON, buffer, string and url encoded data submitted using HTTP
Routers
• Defining routes in the same file is very tedious to maintain. To separate the routes from our main index.js
file, we will use express.Router. Create a new file called books.js and type the following in it.
Filename: books.js
var express = require('express');
var router = express.Router();
router.get('/', function(req, res){
res.send('GET random book.');
});
router.post('/', function(req, res){
res.send(' Add a book.');
});
//export this router to use in our index.js
module.exports = router;
113 Express.js | © Smartcliff | Internal | Version 1.0
Routing and HTTP Methods
Routers
• Now to use this router in our index.js, type the following before the app.listen function call.
Filename: index.js
In this example,
var express = require(‘Express');
• The app.use function call on
var app = express();
route '/books' attaches
var PORT = 3000;
the books router with this route.
var books = require('./books.js');
• Now whatever requests our app
//both index.js and books.js should be in same directory
gets at the '/books', will be
app.use('/books', books);
app.listen(PORT, function(err){ handled by our things.js router.
Routers
• Run the command nodemon index.js and point the browser to http://localhost:3000 and see the following
result.
Template Engine
• At runtime, it replaces variables in a template file with actual values, and transforms the template into an
HTML file sent to the client.
• There are number of template engines available some of them are given below:-
– EJS
– Pug (formerly known as jade)
– Vash
– Mustache
– Dust.js
– Nunjucks
– Handlebars
• Template engine makes us able to use static template files in our application.
• To render template files we have to set the following application setting properties:
For example, to use the Pug template engine: app.set('view engine', 'pug')
npm i pug
• Create a folder named “Views” in project’s root directory Because by default Express.js searches all the
views (templates) in the views folder under the root folder.
• If we don’t want your folder to be named as views we can change name using views property in express.
• Eg : the name of your folder is myviews then in our main file in this case app.js we write
app.set(‘views’,./myviews);
• All the templates file are saved with template engine’s extension and in views folder. Here we are using
pug so all templates are saved with .ejs extension in views folder.
• -
Filename:index.pug
html
- var demo = "Thanks for watching"
head
title Learn Express JS
style
include index.css
body
h1.demo1 Welcome to Template Engine
p#demo2 Join with me, to learn Template engine
a(href="https://smartcliff.in/") Click Here
ul
each val in ['MongoDB','Express','Angular','NodeJS']
li= val
• -
Filename:index.pug
div
input(
type ="text"
placeholder ="Enter your Name"
)
div
h1=Quotes
h2=Topic
div
h1(style={color:'red'}) Hello #{demo}});
• -
Filename:index.css
.demo1{
color: blueviolet;
}
#demo2{
color: brown;
}
.demo3{
color: red;
}
• -
Filename:app.js
var express=require('express');
var app=express();
app.set('view engine','pug');
app.set('views','./views')
app.get('/',function(req,res){
res.render('index',{
Quotes : "Designer can design everything",
Topic : "MEAN Stack"
});
});
app.listen(3000);
123 Express.js | © Smartcliff | Internal | Version 1.0
Express.js Templating
• output
• EJS is a simple templating language that lets you generate HTML markup with plain JavaScript.
• EJS is much more similar to HTML than Pug is, retaining the usual method of opening and closing tags
as well as specifying attributes.
• Variables are declared using angle brackets and the percent sign in this manner: <%= name %>.
npm i ejs
• Create a folder named “Views” in project’s root directory Because by default Express.js searches all the
views (templates) in the views folder under the root folder.
• If we don’t want your folder to be named as views we can change name using views property in express.
• Eg : the name of your folder is myviews then in our main file in this case app.js we write
app.set(‘views’,./myviews);
• All the templates file are saved with template engine’s extension and in views folder. Here we are using
EJS so all templates are saved with .ejs extension in views folder.
• EJS files are simple to write because in this file we write simple HTML and write logic, backend variables
• For demonstration purpose, we have two files one is main JS file i.e. app.js , which creates a server and
one template file( display.ejs ).
Filename:app.js
// To create a basic server like
var express = require("express"); //requiring express module
var app = express(); //creating express instance
//To send templates to frontend, first we set the view engine as follows:
app.set("view engine","ejs");
app.listen(3000, function() {
console.log("Node server is running..");
});
128 Express.js | © Smartcliff | Internal | Version 1.0
Express.js Templating
• After setting the view engine we create a simple display.ejs file in view folder with a simple ‘hello user’
message in it.
Filename:display.ejs
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-
scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>templates</title>
</head>
<body>
<p>Hello User</p>
</body>
</html>
//To send templates to frontend, first we set the view engine as follows:
app.set("view engine","ejs");
• If we want to send data from backend and use it in EJS file we can do this in the following manner:-
• Here instead of user in our display.ejs file I want to specify the name of the user. We can send data
where we are rendering the file.
• Eg:- res.render(‘display’,{variable_name:’value’});
res.render('display',{user:'Alice'});
• And to display this on front end we write this user variable inside <%= %> like this:-
Filename:display.ejs Filename:app.js
<!DOCTYPE html> // To create a basic server like
<html lang="en"> var express = require("express"); //requiring
<head> express module
<meta charset="UTF-8"> var app = express(); //creating express instance
<meta name="viewport"
content="width=device-width, initial- //To send templates to frontend, first we set the
scale=1.0"> view engine as follows:
<meta http-equiv="X-UA-Compatible" app.set("view engine","ejs");
content="ie=edge">
<title>templates</title> app.get("/", function(req, res) {
</head> res.render('display',{user:'Alice'});
<body> });
<p>Hello <%= user%></p> app.listen(3000, function() {
</body> console.log("Node server is running..");
</html> });
Filename:display_author.ejs
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<h3>Name Of Authors</h3>
<ul>
<% authors.forEach(function(author){ %> <!-- looping through authors array -->
<li>
<%= author.name %>
</li>
<% }) %> </ul></body></html>
136 Express.js | © Smartcliff | Internal | Version 1.0
Express.js Templating
• Save app.js and display.ejs with the following code and then run the code, now as we refresh the web
page(http://localhost:3000/authors) you will see the following output.
• To serve static files such as images, CSS files, and JavaScript files, use the express.static built-in
middleware function in Express.
• For example, use the following code to serve images, CSS files,
app.use(express.static('public'))
• For static files, we create a folder with name such as ‘public’. When we set our static files folder as
‘public’ using express.static middleware, all the static files will be served from this public folder itself.
• Suppose, we create a route to display a frontend page, with an image, as shown below:
Filename:app_image.js
var express = require("express");
var app = express();
app.set("view engine","ejs");
app.use(express.static('public'))
app.get('/image', (req, res) => {
res.render('displayImage')
}) app.listen(3000);
Filename:displayimage.ejs
<html>
<head>
<title>Hello World!</title>
</head>
<body>
<h1>SmartCliff Image Below</h1>
<img src=“logo.png" alt=“LOGO" />
</body> </html>
• Notice the image element source to logo.png . Since you’ve served the public directory through Express,
you can add the file name as your image source’s value.
140 Express.js | © Smartcliff | Internal | Version 1.0
Express.js Templating
• We can also set multiple static assets directories using the following program −
app.use(express.static('public'));
app.use(express.static('images'));
app.listen(3000);
• 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 our .js file −
• Now whenever we need to include a file, for example, a script file called .ejs residing in our public
directory, use the following script tag −
• This technique can come in handy when providing multiple directories as static files. These prefixes can
help distinguish between multiple directories.
143 Express.js | © Smartcliff | Internal | Version 1.0
Express.js Templating
• In express, to handle form submission, we use ‘body-parser’ to parse the body received in our route
• A simple demonstration of form handling using a simple form page rendered through GET request on
Filename: form.js
var express = require("express"); app.post('/submit-form', (req, res) => {
var app = express(); res.end(JSON.stringify(req.body))
const bodyParser = require('body-parser') })
app.set("view engine","ejs"); app.listen(3000, function() {
app.use(bodyParser.urlencoded({ extended: false })) console.log("Node server is running..");
app.use(bodyParser.json()) });
app.use(express.json({ extended: false }))
app.get('/formPage', function (req, res) {
res.render('formPage', {
heading: 'Basic Form Example',
})
})
146 Express.js | © Smartcliff | Internal | Version 1.0
Express.js Templating
• And on filling and submitting the form, we get a response from the server on route http://localhost:3000/
submit-form as shown below on right.
Async / Await
• Async functions let us write promise-based code as if it were synchronous, but without blocking the
• Roughly, async functions provide better syntax for code that uses Promises.
Async / Await
async Function:
• Even if you don't explicitly return a Promise within the async function, JavaScript will automatically wrap
Async / Await
await Operator:
• When the JavaScript engine encounters an await keyword, it pauses the execution of the async function
• During this pause, the event loop is not blocked, meaning other asynchronous operations can continue to
execute.Once the Promise resolves, the await expression returns the resolved value of the Promise, and
Async / Await
• If the Promise rejects, the await expression will throw the rejected value as an error. You'll typically
Async / Await
Example:
async function fetchUserData() {
try {
console.log('User:', user);
console.log('Posts:', posts);
} catch (error) {
console.error('Error:', error);
}}
fetchUserData();
Async / Await
• Simplified Error Handling: Uses standard try...catch blocks for error handling, which is more familiar
• Easier Debugging: Stepping through async/await code in a debugger often feels more natural than
• Reduces Boilerplate: Less nesting and fewer .then() calls lead to cleaner code.
• 2. After installing the express module, you can check your express version in command prompt using
the command.
• 3. After that, you can just create a folder and add a file for example, index.js. To run this file you need to
run the following command.
node index.js
npm start
<!DOCTYPE html>
<form method="post" action="/">
<html lang="en">
Name: <input type="text"
<head>
name="nametextbox" ><br>
<meta charset="UTF-8">
Age: <input type="text"
<meta name="viewport"
name="agetextbox" >
content="width=device-width, initial-
<input type="submit">
scale=1.0">
<title>Document</title>
</form>
</head>
</body>
<body>
</html>
• Input
• Output
• File structure
• Following example shows CRUD (Create, Read, Update, Delete) operations on a expense details
(transactions).
• User is allowed to ADD a new expense, VIEW a selected expense, UPDATE a expense and DELETE a
expense details.
<body>
<div class="login-container">
<!-- public/login.html -->
<h2>Login</h2>
<!DOCTYPE html>
<form id="loginForm">
<html lang="en">
<input type="text" id="username"
<head>
placeholder="Username" required />
<meta charset="UTF-8" />
<input type="password" id="password"
<meta name="viewport"
placeholder="Password" required />
content="width=device-width, initial-
<button type="submit">Login</button>
scale=1.0"/>
<p id="error" class="error-
<title>Login</title>
message"></p>
<link rel="stylesheet" href="login.css"
</form>
/>
</div>
</head>
<script src="scripts/login.js"></script>
</body>
document.getElementById('loginForm').addEv
body: JSON.stringify({ username,
entListener('submit', async (e) => {
password })
e.preventDefault();
});
const username =
if (res.redirected) {
document.getElementById('username').value.
window.location.href = res.url; //
trim();
Redirect to dashboard.html
const password =
} else {
document.getElementById('password').value.
const errorText = await res.text();
trim();
document.getElementById('error').tex
tContent = errorText;
const res = await fetch('/login', {
}
method: 'POST',
});
headers: { 'Content-Type':
'application/json' },
Server.js
// Middleware
app.use(bodyParser.urlencoded({ extended:
true }));
const express = require('express'); app.use(bodyParser.json());
const fs = require('fs'); app.use(express.static(path.join(__dirname
const path = require('path'); , 'public'))); // For HTML/CSS/JS
const bodyParser = require('body-parser');
const app = express(); // Helper functions
const PORT = 3000; function readEntries() {
try {
// File paths const data =
const usersPath = path.join(__dirname, fs.readFileSync(entriesPath, 'utf-8');
'data', 'users.json'); return JSON.parse(data);
const entriesPath = path.join(__dirname, } catch (err) {
'data', 'entries.json'); return [];
}
}
Server.js
fs.readFile(usersPath, 'utf-8', (err, data) =>
{
if (err) return res.status(500).send('Error
function saveEntries(entries) {
reading users');
fs.writeFileSync(entriesPath,
JSON.stringify(entries, null, 2));
const users = JSON.parse(data);
}
const user = users.find(u => u.username ===
// ---------- Routes ---------- //
username && u.password === password);
app.get("/", function(req,res)
{
if (user) {
res.redirect("/login.html");
return res.redirect('/dashboard.html');
});
} else {
res.status(401).send('Incorrect username
// 1. Login Route
or password.'); // Optional: show error in UI
app.post('/login', (req, res) => {
}
const { username, password } = req.body;
});
});
Server.js
// 4. Add new entry
// 2. Get all entries app.post('/entries', (req, res) => {
app.get('/entries', (req, res) => { const newEntry = req.body;
const entries = readEntries(); const entries = readEntries();
res.json(entries);
}); const newId = entries.length > 0 ?
// 3. Get entry by ID Math.max(...entries.map(e => e.id || 0)) + 1 :
app.get('/entries/:id', (req, res) => { 1;
const id = parseInt(req.params.id); const entryWithId = { id: newId, ...newEntry
const entries = readEntries(); };
const entry = entries.find(e => e.id ===
id); entries.push(entryWithId);
if (!entry) return saveEntries(entries);
res.status(404).send('Entry not found');
res.json(entry); res.status(201).json(entryWithId);
}); });
Server.js
// 6. Delete entry by ID
// 5. Update entry by ID
app.delete('/entries/:id', (req, res) => {
app.put('/entries/:id', (req, res) => {
const id = parseInt(req.params.id);
const id = parseInt(req.params.id);
const entries = readEntries();
const updatedData = req.body;
const updatedEntries = entries.filter(e =>
const entries = readEntries();
e.id !== id);
const index = entries.findIndex(e => e.id
=== id);
if (entries.length === updatedEntries.length)
{
if (index === -1) return
return res.status(404).send('Entry not
res.status(404).send('Entry not found');
found');
}
entries[index] = { id, ...updatedData };
saveEntries(entries);
saveEntries(updatedEntries);
res.sendStatus(204);
res.json(entries[index]);
});
});
Server.js
// Start server
app.listen(PORT, () => {
console.log(`Server running at
http://localhost:${PORT}`);
});
• Login page
• Dashboard page