0% found this document useful (0 votes)
14 views

Full Stack Unit 2

This document provides an overview of server-side programming with Node.js, covering web server basics, architecture, and the advantages of using Node.js for asynchronous programming. It also introduces desktop application frameworks like NW.js and Electron, highlighting their capabilities and differences. Key points include the ease of creating web and desktop apps using JavaScript, as well as the challenges faced by web apps compared to desktop applications.

Uploaded by

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

Full Stack Unit 2

This document provides an overview of server-side programming with Node.js, covering web server basics, architecture, and the advantages of using Node.js for asynchronous programming. It also introduces desktop application frameworks like NW.js and Electron, highlighting their capabilities and differences. Key points include the ease of creating web and desktop apps using JavaScript, as well as the challenges faced by web apps compared to desktop applications.

Uploaded by

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

Unit - 2

SERVER SIDE PROGRAMMING WITH NODE JS


Introduction to Web Servers – Javascript in the Desktop with NodeJS – NPM – Serving files with
the http module – Introduction to the Express framework – Server-side rendering with Templating
Engines – Static Files - async/await - Fetching JSON from Express

Introduction to Web Servers

Web server is a computer where the web content is stored. Basically web server is
used to host the web sites but there exists other web servers also such as gaming,
storage, FTP, email etc.

Web site is collection of web pages whileweb server is a software that


respond to the request for web resources.

Web Server Working

Web server respond to the client request in either of the following two ways:

Sending the file to the client associated with the requested URL.

Generating response by invoking a script and communicating with

database

Key Points

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
1
contact to the application server and data store to construct the HTTP
response.

Architecture

Web Server Architecture follows the following two approaches:

Concurrent Approach

Single-Process-Event-Driven Approach.

Concurrent Approach

Concurrent approach allows the web server to handle multiple client requests at the
same time. It can be achieved by following methods:

Multi-process

Multi-threaded

Hybrid method.

Multi-processing

In this a single process (parent process) initiates several single-threaded child


processes and distribute incoming requests to these child processes. Each of the child
processes are responsible for handling single request.

It is the responsibility of parent process to monitor the load and decide if processes
should be killed or forked.

Multi-threaded

Unlike Multi-process, it creates multiple single-threaded process.

Hybrid

It is combination of above two approaches. In this approach multiple process are


created and each process initiates multiple threads. Each of the threads handles one
connection. Using multiple threads in single process results in less load on system
resources.

Examples

Following table describes the most leading web servers available today:
S.N. Web Server Descriptino
Apache HTTP Server
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
1 installed on almost all operating systems including Linux, UNIX, Windows,
FreeBSD, Mac OS X and more. About 60% of the web server machines run the
Apache Web Server.
2
Internet Information Services (IIS)
The Internet Information Server (IIS) is a high performance Web Server from
2. 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 operating
system so it is relatively easy to administer it.
Lighttpd
The lighttpd, pronounced lighty is also a free web server that is distributed with
3. the FreeBSD operating system. This open source web server is fast, secure and
consumes much less CPU power. Lighttpd can also run on Windows, Mac OS X,
Linux and Solaris operating systems.
Sun Java System Web Server
This web server from Sun Microsystems is suited for medium and large web
4. sites. Though the server is free it is not open source. 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, Perl, Python, and Ruby on Rails, ASP and Coldfusion etc.
Jigsaw Server
Jigsaw (W3C's Server) comes from the World Wide Web Consortium. It is open
5. source and free and can run on various platforms like Linux, UNIX, Windows,
and Mac OS X Free BSD etc. Jigsaw has been written in Java and can run CGI
scripts and PHP programs.

Javascript in the Desktop with NodeJS

Node.js is an open source server environment.

Node.js allows you to run JavaScript on the server.

What is Node.js?

 Node.js is an open source server environment


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

Why Node.js?

Node.js uses asynchronous programming!


A common task for a web server can be to open a file on the server and return the
content to the client.

Here is how PHP or ASP handles a file request:

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


2. Waits while the file system opens and reads the file.
3. Returns the content to the client.
4. Ready to handle the next request.

Here is how Node.js handles a file request:

3
1. Sends the task to the computer's file system.
2. Ready to handle the next request.
3. When the file system has opened and read the file, the server returns the
content to the client.

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

Node.js runs single-threaded, non-blocking, asynchronous programming, which is


very memory efficient.

What Can Node.js Do?

 Node.js can generate dynamic page content


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

What is a Node.js File?

 Node.js files contain tasks that will be executed on certain events


 A typical event is someone trying to access a port on the server
 Node.js files must be initiated on the server before having any effect
 Node.js files have extension ".js"

Web apps have thrived for a number of reasons:

 Internet speeds improved and access increased, and, importantly, the cost of
internet access went down, making the user base grow massively, unlike most
other communication channels.
 Web browsers have benefitted from increased competition. As appealing
alternatives to Internet Explorer emerged, new features were added to those
browsers, which in turn enabled web apps to do new things.
 The relative ease of learning HTML, CSS, and JavaScript lowered the barrier
of entry for developers to make web apps, as opposed to learning lower-level
languages like C and C++.
 The rise of open source software meant that the cost of distributing and
obtaining software declined significantly, meaning that developers with a bit
of cash, time, and the right level of skill could build their own web app
There are still things that challenge and limit the ability of web apps today:

 Internet access is not always available. If you’re on a train and you go under a
tunnel, chances are you’ll lose internet access. If your web app depends on
saving data, hopefully it will be able to store a local copy of the changes and
allow for them to be synchronized via the internet when access resumes.
 If your app has a lot of features, the amount of data it will need to transfer over
the internet to run the app could be large and may slow down the loading of
the app. If it takes too long, people load something else—something proven by
research into the impact that slow web page loading times have on e-
commerce transactions.
 If you’re working with large files (such as high-resolution images and videos)
that are sitting on your desktop computer, then it might not make sense for
them to be uploaded to the internet in order for a web app to edit them.
4
 Because of the security policy of the web browser, there are limits to what
hardware/software features of the computer the web app can access.
 You have no control over what web browsers a user may use to visit your web
app. You have to use feature detection to cater to different web browsers,
which restricts what features your app can use. The user experience (UX) can
vary wildly.

Web apps are essentially restricted by the limits of internet access and browser
features. It is in these circumstances that a desktop app may be preferable to a web
app. Some of the benefits include the following:

 You don’t require internet access to start and run the app.
 Desktop apps start instantly, without having to wait for resources to download
from the internet.
 Desktop apps have access to the computer’s OS and hardware resources,
including access to the files and folder on the user’s computer.
 You have greater control over the UX with the software. You don’t have to
worry about how different browsers handle CSS rules and what JavaScript
features they support.
 Once a desktop app is installed on a user’s computer, it’s there. It doesn’t
depend on you running web servers to support the app, where you need to
offer 24/7 support in case your web app goes down, or worse, your web-
hosting provider encounters technical difficulties.

Usually, desktop apps have required developers to be proficient in languages like C++,
Objective-C, or C#, and knowing frameworks like .NET, Qt, Cocoa, or GTK. For
some developers, that can be a barrier to entry and may discourage them from
considering the possibility of building a desktop app.

n the Node.js ecosystem, there are two major frameworks for creating desktop apps:
NW.js and Electron. Both are supported by major businesses (NW.js by Intel and
Gnor Tech, and Electron by GitHub), both have large communities around them, and
both share similar approaches to building desktop apps.
The great thing about Node.js desktop application frameworks like Electron and
NW.js is that they have significantly lowered that barrier of entry for developers. By
allowing developers to create apps using HTML, CSS, and JavaScript, they’ve opened
the door for web developers to also be desktop app developers, with the added benefit
of being able to use the same code across both the web app and desktop app
platforms.

NW.js

NW.js is a framework for building desktop apps with HTML, CSS, and JavaScript. It
was created back in November 2011 by Roger Wang at Intel’s Open Source
Technology Center in China.

Node.js comes with a package management tool called npm that handles installing
libraries for Node.js, and NW.js can be installed using it. On your computer, open the
command-line program for your OS (Command Prompt or PowerShell on Windows,
and Terminal on both Mac OS and Linux).

After you’ve opened your command-line program, run the following command:
5
npm install –g nw

This will ins tall NW.js on your computer as a Node.js module available to all of your
Node.js desktop apps.

Creating the Hello World app

The app is so small that you can create the files by hand. At the bare minimum, you
only need two files:

 A file named package.json— This contains configuration information about


the app, and is required by NW.js.
 An HTML file— This file will be loaded by the package.json file and
displayed in the app window. In this case, it’s a file called index.html (but it
can be named something else, such as app.html or main.html).

Start by creating a folder for the app’s file. On your computer, go where you like to
store your project source code and create a folder named hello-world-nwjs. Then you
can create the package.json file that will be stored inside the hello-world-nwjs folder.

In your text editor/IDE, create a file named package.json inside the hello-world-nwjs
folder and insert the following code into it:

{
"name" : "hello-world-nwjs",
"main" : "index.html",
"version" : "1.0.0"
}

The package.json file consists of some configuration information about the app: its
name, the main file to load when the app starts, and its version number. These fields
are required by NW.js (though the version field is required by npm). The name field
must contain lowercase alphanumeric characters only—there can be no space
characters in the name.

The main field contains the file path for the entry point of your app. In the case of
NW.js, you have the option of loading either a JavaScript file or an HTML file, but
HTML files tend to be the common choice for NW.js apps. The HTML file is loaded
into the app window, and to demonstrate this, you’ll create an HTML file called
index.html that will be loaded.

Inside the hello-world-nwjs folder, create a file named index.html and insert the code
in the following listing.

Listing 1.1. Code for the Hello World app’s index.html file

<html>
<head>
<title>Hello World</title>
<style>
body {
background-image: linear-gradient(45deg, #EAD790 0%, #EF8C53 100%);
6
text-align: center;
}
button {
background: rgba(0,0,0,0.40);
box-shadow: 0px 0px 4px 0px rgba(0,0,0,0.50);
border-radius: 8px;
color: white;
padding: 1em 2em;
border: none;
font-family: 'Roboto', sans-
serif; font-weight: 100;
font-size: 14pt;
position: relative;
top: 40%;
cursor: pointer;
outline: none;
}
button:hover {
background: rgba(0,0,0,0.30);
}
</style>
<link href='https://fonts.googleapis.com/css?family=Roboto:300' rel='stylesheet'
type='text/css'>
<script>
function sayHello () {
alert('Hello World');
}
</script>
</head>
<body>
<button onclick="sayHello()">Say Hello</button>
</body>
</html>

Once you’ve saved the index.html file on your computer, you can run the app on your
computer. Inside the hello-world-nwjs folder, run the following command on your
terminal:

nw

7
Electron

Electron is a desktop app framework from GitHub. It was built for GitHub’s text
editor Atom and was originally known as Atom Shell. It allows you to build cross-
platform desktop apps using HTML, CSS, and JavaScript.

How does Electron work and differ from NW.js?

One of the things that Electron did differently from NW.js was the way it got
Chromium and Node.js to work together. In NW.js, Chromium is patched so that
Node.js and Chromium are sharing the same JavaScript context (or state, as you may
call it in programming). In Electron, there’s no patching of Chromium involved;
instead, it’s combined with Node.js through Chromium’s content API and the use of
Node.js’s node_bindings.

Another important difference between NW.js and Electron is that where NW.js
usually uses an HTML file as the entry point for loading a desktop app, Electron uses
a JavaScript file instead. Electron delegates the responsibility of loading an app
window to code that’s executed inside the JavaScript file.

A Hello World app in Electron

In your terminal or at the Command Prompt, run the following command:

npm install –g electron

This will install Electron as a global npm module, meaning that it will be available to
other Node.js applications where you want to use it. Once you have installed the
Electron module, we can take a look at what an example Hello World app’s files
consist of. Here’s the bare minimum number of files required to run an Electron app:

 index.html
 main.js
 package.json

You can create a folder named hello-world-electron to store the app’s files. Create a
8
folder with the suggested name, and then you’ll add the required files inside it.

We’ll start with the package.json. Here’s what an example package.json looks like:

{
"name" : "hello-world",
"version" : "1.0.0",
"main" : "main.js"
}

You might notice that package.json looks almost identical to the package.json file
used to load the Hello World app in NW.js. The only difference is that where an
NW.js app’s package.json field expects the main property to specify an HTML file as
the app’s entry point, Electron expects the main property to specify a JavaScript file.

In Electron, the JavaScript file is responsible for loading an app’s windows, tray
menus, and other items, as well as handling any system-level events that occur in the
OS. For the Hello World example, it looks like the following.

Listing 1.2. main.js file for the Hello World Electron app

'use strict';const electron = require('electron');const app = electron.app;const


BrowserWindow = electron.BrowserWindow;let mainWindow = null;
app.on('window-all-closed', () => {
if (process.platform !== 'darwin') app.quit();
});
app.on('ready', () => {
mainWindow = new BrowserWindow();
mainWindow.loadURL(`file://${ dirname}/index.html`);
mainWindow.on('closed', () => { mainWindow = null; });
});
Having created the main.js file that’s the entry point to your app, you’ll now create
the index.html file that the main.js file loads in an app window. Create a file named
index.html, and insert the code shown next.

Listing 1.3. index.html for the Hello World Electron app

<html>
<head>
<title>Hello World</title>
<style>
body {
background-image: linear-gradient(45deg, #EAD790 0%, #EF8C53 100%);
text-align: center;
}

button {
background: rgba(0,0,0,0.40);
box-shadow: 0px 0px 4px 0px rgba(0,0,0,0.50);
border-radius: 8px;
color: white;
padding: 1em 2em;
9
border: none;
font-family: 'Roboto', sans-
serif; font-weight: 300;
font-size: 14pt;
position: relative;
top: 40%;
cursor: pointer;
outline: none;
}

button:hover {
background: rgba(0,0,0,0.30);
}
</style>
<link href='https://fonts.googleapis.com/css?family=Roboto:300' rel='stylesheet'
type='text/css' />
<script>
function sayHello () {
alert('Hello World');
}
</script>
</head>
<body>
<button onclick="sayHello()">Say Hello</button>
</body></html>

This is the HTML file that will be loaded into the browser window by the main.js file.
It’s the same code that’s used in the NW.js example app’s index.html file (so we can
compare the examples across both frameworks). With the files saved in the
application folder, you can now run the app from the command line.

To execute the app from the command line, cd into the hello-world-electron directory,
and run the following command:

electron

If you open the app in Windows 10, you can expect to see a result similar to the one
displayed for the Linux app example, as shown in figure 1.11.

Figure 1.11. The Hello World app running on Electron and Windows 10. Like
the Linux app example, the Windows example displays a menu in the app
window.

10
NPM

What is NPM?

NPM is a package manager for Node.js packages, or modules if you like.

www.npmjs.com hosts thousands of free packages to download and use.

The NPM program is installed on your computer when you install Node.js

NPM is already ready to run on your computer!

What is a Package?

A package in Node.js contains all the files you need for a module.

Modules are JavaScript libraries you can include in your project.

Download a Package

Downloading a package is very easy.

Open the command line interface and tell NPM to download the package you want.

I want to download a package called "upper-case":


11
Download "upper-case":

C:\Users\Your Name>npm install upper-case

Now you have downloaded and installed your first package!

NPM creates a folder named "node_modules", where the package will be placed. All
packages you install in the future will be placed in this folder.

My project now has a folder structure like this:

C:\Users\My Name\node_modules\upper-case

Using a Package

Once the package is installed, it is ready to use.

Include the "upper-case" package the same way you include any other module:

var uc = require('upper-case');

Create a Node.js file that will convert the output "Hello World!" into upper-case
letters:

Example

var http = require('http');


var uc = require('upper-case');
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/html'});
res.write(uc.upperCase("Hello World!"));
res.end();
}).listen(8080);
Save the code above in a file called "demo_uppercase.js", and initiate the file:

Initiate demo_uppercase:

C:\Users\Your Name>node demo_uppercase.js

If you have followed the same steps on your computer, you will see the same result as
the example: http://localhost:8080

What is a Module in Node.js?

Consider modules to be the same as JavaScript libraries.

A set of functions you want to include in your application.

Built-in Modules

Node.js has a set of built-in modules which you can use without any further
installation.
12
Include Modules

To include a module, use the require() function with the name of the module:

var http = require('http');

Now your application has access to the HTTP module, and is able to create a server:

http.createServer(function (req, res) {


res.writeHead(200, {'Content-Type': 'text/html'});
res.end('Hello World!');
}).listen(8080);

Create Your Own Modules

You can create your own modules, and easily include them in your applications.

The following example creates a module that returns a date and time object:

Example

Create a module that returns the current date and time:

exports.myDateTime = function () {
return Date();
};

Use the exports keyword to make properties and methods available outside the
module file.
Save the code above in a file called "myfirstmodule.js"

Include Your Own Module

Now you can include and use the module in any of your Node.js files.

Example

Use the module "myfirstmodule" in a Node.js file:

var http = require('http');


var dt = require('./myfirstmodule');

http.createServer(function (req, res) {


res.writeHead(200, {'Content-Type': 'text/html'});
res.write("The date and time are currently: " + dt.myDateTime());
res.end();
}).listen(8080);

Notice that we use ./ to locate the module, that means that the module is located in the
same folder as the Node.js file.

13
Save the code above in a file called "demo_module.js", and initiate the file:

Initiate demo_module.js:

C:\Users\Your Name>node demo_module.js

If you have followed the same steps on your computer, you will see the same result as
the example: http://localhost:8080

Serving files with the http module

The Built-in HTTP Module

Node.js has a built-in module called HTTP, which allows Node.js to transfer data over
the Hyper Text Transfer Protocol (HTTP).

To include the HTTP module, use the require() method:

var http = require('http');

Node.js as a Web Server

The HTTP module can create an HTTP server that listens to server ports and gives a
response back to the client.

Use the createServer() method to create an HTTP server:


Example

var http = require('http');

//create a server object:


http.createServer(function (req, res) {
res.write('Hello World!'); //write a response to the client
res.end(); //end the response
}).listen(8080); //the server object listens on port 8080

The function passed into the http.createServer() method, will be executed when
someone tries to access the computer on port 8080.

Save the code above in a file called "demo_http.js", and initiate the file:

Initiate demo_http.js:

C:\Users\Your Name>node demo_http.js

If you have followed the same steps on your computer, you will see the same result as
the example: http://localhost:8080

Add an HTTP Header

14
If the response from the HTTP server is supposed to be displayed as HTML, you
should include an HTTP header with the correct content type:

Example

var http = require('http');


http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/html'});
res.write('Hello World!');
res.end();
}).listen(8080);

The first argument of the res.writeHead() method is the status code, 200 means that all
is OK, the second argument is an object containing the response headers.

Read the Query String

The function passed into the http.createServer() has a req argument that represents the
request from the client, as an object (http.IncomingMessage object).

This object has a property called "url" which holds the part of the url that comes after
the domain name:

demo_http_url.js

15
var http = require('http');
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/html'});
res.write(req.url);
res.end();
}).listen(8080);

Save the code above in a file called "demo_http_url.js" and initiate the file:

Initiate demo_http_url.js:

C:\Users\Your Name>node demo_http_url.js

If you have followed the same steps on your computer, you should see two different
results when opening these two addresses:

http://localhost:8080/summer

Will produce this result:

/summer

http://localhost:8080/winter

Will produce this result:

/winter

Split the Query String

There are built-in modules to easily split the query string into readable parts, such as
the URL module.

Example

Split the query string into readable parts:

var http = require('http');


var url = require('url');

http.createServer(function (req, res) {


res.writeHead(200, {'Content-Type': 'text/html'});
var q = url.parse(req.url, true).query;
var txt = q.year + " " + q.month;
res.end(txt);
}).listen(8080);

Save the code above in a file called "demo_querystring.js" and initiate the file:

Initiate demo_querystring.js:

16
C:\Users\Your Name>node demo_querystring.js

The address: http://localhost:8080/?

year=2017&month=July

Will produce this result:

2017 July

Node.js as a File Server

The Node.js file system module allows you to work with the file system on your
computer.

To include the File System module, use the require() method:

var fs = require('fs');

Common use for the File System module:

 Read files
 Create files
 Update files
 Delete files
 Rename files

Read Files

The fs.readFile() method is used to read files on your computer.

Assume we have the following HTML file (located in the same folder as Node.js):

demofile1.html

<html>
<body>
<h1>My Header</h1>
<p>My paragraph.</p>
</body>
</html>

Create a Node.js file that reads the HTML file, and return the content:

Example

var http = require('http');


var fs = require('fs');
http.createServer(function (req, res) {
fs.readFile('demofile1.html', function(err, data) {

17
res.writeHead(200, {'Content-Type': 'text/html'});
res.write(data);
return res.end();
});
}).listen(8080);

Save the code above in a file called "demo_readfile.js", and initiate the file:

Initiate demo_readfile.js:

C:\Users\Your Name>node demo_readfile.js

If you have followed the same steps on your computer, you will see the same result as
the example: http://localhost:8080

Create Files

The File System module has methods for creating new files:

 fs.appendFile()
 fs.open()
 fs.writeFile()

The fs.appendFile() method appends specified content to a file. If the file does not
exist, the file will be created:

Example

Create a new file using the appendFile() method:

var fs = require('fs');

fs.appendFile('mynewfile1.txt', 'Hello content!', function (err) {


if (err) throw err;
console.log('Saved!');
});

The fs.open() method takes a "flag" as the second argument, if the flag is "w" for
"writing", the specified file is opened for writing. If the file does not exist, an empty
file is created:

Example

Create a new, empty file using the open() method:

var fs = require('fs');

fs.open('mynewfile2.txt', 'w', function (err, file) {


if (err) throw err;
console.log('Saved!');
});

18
The fs.writeFile() method replaces the specified file and content if it exists. If the file
does not exist, a new file, containing the specified content, will be created:

Example

Create a new file using the writeFile() method:

var fs = require('fs');

fs.writeFile('mynewfile3.txt', 'Hello content!', function (err) {


if (err) throw err;
console.log('Saved!');
});

Update Files

The File System module has methods for updating files:

 fs.appendFile()
 fs.writeFile()

The fs.appendFile() method appends the specified content at the end of the specified
file:

Example

Append "This is my text." to the end of the file "mynewfile1.txt":

var fs = require('fs');

fs.appendFile('mynewfile1.txt', ' This is my text.', function (err) {


if (err) throw err;
console.log('Updated!');
});

The fs.writeFile() method replaces the specified file and content:

Example

Replace the content of the file "mynewfile3.txt":

var fs = require('fs');

fs.writeFile('mynewfile3.txt', 'This is my text', function (err) {


if (err) throw err;
console.log('Replaced!');
});
Delete Files

To delete a file with the File System module, use the fs.unlink() method.

The fs.unlink() method deletes the specified file:


19
Example

Delete "mynewfile2.txt":

var fs = require('fs');

fs.unlink('mynewfile2.txt', function (err) {


if (err) throw err;
console.log('File deleted!');
});

Rename Files

To rename a file with the File System module, use the fs.rename() method.

The fs.rename() method renames the specified file:

Example

Rename "mynewfile1.txt" to "myrenamedfile.txt":

var fs = require('fs');

fs.rename('mynewfile1.txt', 'myrenamedfile.txt', function (err) {


if (err) throw err;
console.log('File Renamed!');
});

Introduction to the Express framework

Express is a minimal and flexible Node.js web application framework that provides a
robust set of features to develop web and mobile applications. It facilitates the rapid
development of Node based Web applications. Following are some of the core
features of Express framework −

Allows to set up middlewares to respond to HTTP Requests.

Defines a routing table which is used to perform different actions based on


HTTP Method and URL.

Allows to dynamically render HTML Pages based on passing arguments to


templates.
Installing Express

Firstly, install the Express framework globally using NPM so that it can be used to
create a web application using node terminal.

$ npm install express --save

The above command saves the installation locally in the node_modules directory and
creates a directory express inside node_modules. You should install the following
important modules along with express −
20
body-parser − This is a node.js middleware for handling JSON, Raw, Text
and URL encoded form data.

cookie-parser − Parse Cookie header and populate req.cookies with an object


keyed by the cookie names.

multer − This is a node.js middleware for handling multipart/form-data.

$ npm install body-parser --save


$ npm install cookie-parser --save
$ npm install multer --save

Hello world Example

Following is a very basic Express app which starts a server and listens on port 8081
for connection. This app responds with Hello World! for requests to the homepage.
For every other path, it will respond with a 404 Not Found.

var express = require('express');var app = express();

app.get('/', function (req, res) {


res.send('Hello World');})
var server = app.listen(8081, function () {
var host = server.address().address
var port = server.address().port

console.log("Example app listening at http://%s:%s", host, port)})

Save the above code in a file named server.js and run it with the following command.

$ node server.js

You will see the following output −

Example app listening at http://0.0.0.0:8081

Open http://127.0.0.1:8081/ in any browser to see the following result.

Request & Response


21
Express application uses a callback function whose parameters are request and
response objects.

app.get('/', function (req, res) {


// --
})

Request Object − The request object represents the HTTP request and has
properties for the request query string, parameters, body, HTTP headers, and
so on.

Response Object − The response object represents the HTTP response that an
Express app sends when it gets an HTTP request.

You can print req and res objects which provide a lot of information related to HTTP
request and response including cookies, sessions, URL, etc.

Basic Routing

We have seen a basic application which serves HTTP request for the homepage.
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).

We will extend our Hello World program to handle more types of HTTP requests.

var express = require('express');var app = express();


// This responds with "Hello World" on the homepage
app.get('/', function (req, res) {
console.log("Got a GET request for the homepage");
res.send('Hello GET');})
// This responds a POST request for the homepage
app.post('/', function (req, res) {
console.log("Got a POST request for the homepage");
res.send('Hello POST');})
// This responds a DELETE request for the /del_user page.
app.delete('/del_user', function (req, res) {
console.log("Got a DELETE request for /del_user");
res.send('Hello DELETE');})
// This responds a GET request for the /list_user page.
app.get('/list_user', function (req, res) {
console.log("Got a GET request for /list_user");
res.send('Page Listing');})
// This responds a GET request for abcd, abxcd, ab123cd, and so on
app.get('/ab*cd', function(req, res) {
console.log("Got a GET request for /ab*cd");
res.send('Page Pattern Match');})
var server = app.listen(8081, function () {
var host = server.address().address
var port = server.address().port

22
console.log("Example app listening at http://%s:%s", host, port)})

Save the above code in a file named server.js and run it with the following command.

$ node server.js

You will see the following output −

Example app listening at http://0.0.0.0:8081

Now you can try different requests at http://127.0.0.1:8081 to see the output generated
by server.js. Following are a few screens shots showing different responses for
different URLs.

Screen showing again http://127.0.0.1:8081/list_user

Screen showing again http://127.0.0.1:8081/abcd

Screen showing again http://127.0.0.1:8081/abcdefg

23
Server-side rendering with Templating Engines

A template engine enables you to use static template files in your application. At
runtime, the template engine replaces variables in a template file with actual values,
and transforms the template into an HTML file sent to the client. This approach
makes it easier to design an HTML page.

Some popular template engines that work with Express are Pug, Mustache, and EJS.

To render template files, set the following application setting properties, set in app.js
in the default app created by the generator:
 views, the directory where the template files are located. Eg: app.set('views',
'./views'). This defaults to the views directory in the application root directory.
 view engine, the template engine to use. For example, to use the Pug template
engine: app.set('view engine', 'pug').

Pug

Pug has a very distinct syntax, favoring indentation and spaces over the traditional
angle brackets in HTML tags. A typical page with head and body segments looks like
this:

doctype html
html
head
meta(name='viewport', content='width=device-width')
link(rel="stylesheet",
href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css")
title= subject
body
div.container.mt-2
header
h2 Welcome
p Here is the homepage for #{name}
section
h2 Here is the body
24
p Lorem ipsum dolor sit, amet consectetur adipisicing elit. Totam,
repellendus!
footer
h2 Here is the footer p
a(href=link) Unsubscribe

From the example above, you can see there are no opening or closing tags. Instead,
the enclosing tag is declared, and its children are indented just below, like in Python.
The content of each tag is declared beside the tag, while attributes are declared inside
parentheses. Classes are indicated with . and ids with #.

Variables can be defined in two ways:

 Using the equals (=) sign – This is usually used when the variable to be
declared is the only content of the corresponding tag or attribute, as seen in
our title and a tags
 Using the #{variable} syntax – This method can be used both when the
variable is the only content of the tag/attribute and when it is a part of a longer
string

To render the above content in Express, first install the Pug package from npm:

npm i pug

Next, copy the code above into an index.pug file inside the views folder, and in app.js,
register Pug as the preferred template engine:

app.set('view engine', 'pug');


app.set('views', path.join( dirname, 'views'));

In the same file, create a route that renders the file this way:

app.get('/index', (request, response) => {


response.render('index', {
subject: 'Pug template engine',
name: 'our template',
link: 'https://google.com'
});});

The render method takes the name of the file (without the extension) and then the
values of the variables in the template file.

Visit localhost:5000/index and you should get something like this:

25
EJS

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 %>.

EJS tags can be used in different ways:

 <%= – Escape the provided value, and output it to the template


 <%- – Output the provided value without escaping. It is advised you escape all
HTML variables before rendering to prevent cross-site scripting (XSS) attacks
 <% – Perform control operations such as using a conditional or loop

Integrating EJS into Express

First, install the ejs package from npm:


npm i ejs

Next, switch the app view engine setting from Pug to EJS:

app.set('view engine', 'ejs');

Now, to rewrite our Pug code above in EJS, create an index.ejs file in your views
folder and add the following code:

<!DOCTYPE html><html>
<head>
<meta name="viewport" content="width=device-width" />
<link
rel="stylesheet"

href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css"
/>
<title><%= subject %></title>
</head>
<body>
<div class="container mt-2">
<header>
<h2>Welcome</h2>
<p>Here is the homepage for <%= name %></p>
</header>
<section>
<h2>Here is the body</h2>
<p>
Lorem ipsum dolor sit, amet consectetur adipisicing elit. Totam,
repellendus!
</p>
</section>
<footer>
<h2>Here is the footer</h2>
<p><a href="<%= link %>">Unsubscribe</a></p>
26
</footer>
</div>
</body></html>

Now, when you start your server and visit the /index route, the page should be
rendered with similar content with the Pug template.

Handlebars

Handlebars, like EJS, tries to stay faithful to the usual HTML style with a simple way
of inserting variables using two braces — e.g., {{variable}} — or three braces for
HTML-unescaped characters. It is built on the mustache templating engine, so they
share some similarities.
There are a number of npm packages available for compiling and rendering
Handlebars in Express, but I’ll be using the hbs package. This is installed via the
command:

npm i hbs

We then set our view engine to hbs with:

app.set('view engine', 'hbs');

An index.hbs rewrite of our previous index pages would look like this:

<!DOCTYPE html><html><head>
<meta name="viewport" content="width=device-width" />
<link rel="stylesheet"
href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" />
<title>
{{subject}}
</title></head><body>
<div class="container mt-2">
<header>
<h2>Welcome</h2>
<p>Here is the homepage for {{name}}
</p>
</header>
<section>
<h2>Here is the body</h2>
<p>
Lorem ipsum dolor sit, amet consectetur adipisicing elit. Totam,
repellendus!
</p>
</section>
<footer>
<h2>Here is the footer</h2>
<p><a href="{{link}}">Unsubscribe</a></p>
</footer>
</div></body></html>

Visiting the /index route should render a page similar to the same route in the Pug
27
application.

Static Files

To serve static files such as images, CSS files, and JavaScript files, use the
express.static built-in middleware function in Express.
The function signature is:

express.static(root, [options])

The root argument specifies the root directory from which to serve static assets.

The following table describes the properties of the options object.


Property Description Type Default
Determines how dotfiles (files or directories that
dotfiles begin with a dot “.”) are treated. String “ignore”

Enable or disable etag generation


etag Boolean true
NOTE: express.static always sends weak ETags.
Sets file extension fallbacks: If a file is not found,
extensions search for files with the specified extensions and Mixed false
serve the first one found. Example: ['html', 'htm'].
Let client errors fall-through as unhandled
fallthrough requests, otherwise forward a client error. Boolean true
Enable or disable the immutable directive in the
Cache-Control response header. If enabled, the
maxAge option should also be specified to enable
immutable caching. The immutable directive will prevent Boolean false
supported clients from making conditional
requests during the life of the maxAge option to
check if the file has changed.

28
Sends the specified directory index file. Set to
index false to disable directory indexing. Mixed “index.html”
Set the Last-Modified header to the last modified
lastModified date of the file on the OS. Boolean true
Set the max-age property of the Cache-Control
maxAge header in milliseconds or a string in ms format. Number 0
Redirect to trailing “/” when the pathname is a
redirect directory. Boolean true
Function for setting HTTP headers to serve with
setHeaders the file. Function

For example, use the following code to serve images, CSS files, and JavaScript files
in a directory named public:

app.use(express.static('public'))

Now, you can load the files that are in the public directory:

http://localhost:3000/images/kitten.jpg

http://localhost:3000/css/style.css
http://localhost:3000/js/app.js
http://localhost:3000/images/bg.png
http://localhost:3000/hello.html
Express looks up the files relative to the static directory, so the name of the static
directory is not part of the URL.

To use multiple static assets directories, call the express.static middleware function
multiple times:

app.use(express.static('public'))
app.use(express.static('files'))

Express looks up the files in the order in which you set the static directories with the
express.static middleware function.

To create a virtual path prefix (where the path does not actually exist in the file
system) for files that are served by the express.static function, specify a mount path
for the static directory, as shown below:

app.use('/static', express.static('public'))

Now, you can load the files that are in the public directory from the /static path prefix.

http://localhost:3000/static/images/kitten.jpg
http://localhost:3000/static/css/style.css
http://localhost:3000/static/js/app.js
http://localhost:3000/static/images/bg.png
http://localhost:3000/static/hello.html
29
However, the path that you provide to the express.static function is relative to the
directory from where you launch your node process. If you run the express app from
another directory, it’s safer to use the absolute path of the directory that you want to
serve:

const path = require('path')


app.use('/static', express.static(path.join( dirname, 'public')))

async/await

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.’);

An async function returns a promise, like in this example:

JS
const doSomethingAsync = () => {
return new Promise(resolve => {
setTimeout(() => resolve('I did something'), 3000);
30
});
};

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.

When you want to call this function you prepend await, and the calling code will
stop until the promise is resolved or rejected. One caveat: the client function must
be defined as async. Here's an example:

JS
const doSomething = async () => {
console.log(await doSomethingAsync());
};
Example: After async/await

async function fun1(req, res){


let response = await request.get('http://localhost:3000');
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.

This is a simple example of async/await used to run a function asynchronously:

const doSomethingAsync = () => {


return new Promise(resolve => {
setTimeout(() => resolve('I did something'), 3000)
})
}

const doSomething = async () => {


console.log(await
}

console.log('Before')
doSomething()
console.log('After')

31
Fetching JSON from Express

The express.json() function is a built-in middleware function in Express. It parses


incoming requests with JSON payloads and is based on body-parser.

Syntax:

express.json( [options] )

Parameters: The options parameter have various property like inflate, limit, type, etc.

Return Value: It returns an Object.


Installation of express module:

1. You can visit the link to Install express module. You can install this
package by using this command.

npm install express

2. After installing the express module, you can check your express
version in command prompt using the command.

npm version express

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

Example 1: Filename: index.js

var express = require('express');


var app = express();
var PORT = 3000;

app.use(express.json());

app.post('/', function (req, res) {


console.log(req.body.name)
res.end();
})

app.listen(PORT, function(err){
if (err) console.log(err);
console.log("Server listening on PORT", PORT);
});

Steps to run the program:

1. The project structure will look like this:

32
2. Make sure you have installed express module using the following
command:
npm install express

3. Run index.js file using below command:

node index.js

Output:

Server listening on PORT 3000

4. Now make a POST request to http://localhost:3000/ with header set to


‘content-type: application/json’ and body
{“name”:”GeeksforGeeks”}, then you will see the following output
on your console:

Server listening on PORT 3000


GeeksforGeeks

Example 2: Filename: index.js

var express = require('express');


var app = express();
var PORT = 3000;

// Without this middleware


// app.use(express.json());
app.post('/', function (req, res) {
console.log(req.body.name)
res.end();
})

app.listen(PORT, function(err){
if (err) console.log(err);
console.log("Server listening on PORT", PORT);
});

Run index.js file using below command:

node index.js

Now make a POST request to http://localhost:3000/ with header set to ‘content-type:


33
application/json’ and body {“name”:”GeeksforGeeks”}, then you will see the
following output on your console:

Server listening on PORT 3000


TypeError: Cannot read property 'name' of undefined

The res.json() function sends a JSON response. This method sends a response (with
the correct content-type) that is the parameter converted to a JSON string using the
JSON.stringify() method.
Syntax:

res.json( [body] )

Parameters: The body parameter is the body which is to be sent in the response.
Return Value: It returns an Object.
Installation of express module:

1. You can visit the link to Install express module. You can install this package by
using this command.

npm install express

2. After installing the express module, you can check your express version in
command prompt using the command.

npm version express

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

Example 1: Filename: index.js

var express = require('express');


var app = express();
var PORT = 3000;

// Without middleware
app.get('/', function(req, res){
res.json({ user: 'geek' });
});

app.listen(PORT, function(err){
if (err) console.log(err);
console.log("Server listening on PORT", PORT);
});
Steps to run the program:

34
1. The project structure will look like this:

2. Make sure you have installed express module using the following command:

npm install express

3. Run index.js file using below command:

node index.js

Output:

Server listening on PORT 3000

4. Now open browser and go to http://localhost:3000/, now on your screen you will
see the following output:

{"user":"geek"}

Example 2: Filename: index.js

var express = require('express');


var app = express();
var PORT = 3000;

// With middleware

35
app.use('/', function(req, res, next){
res.json({title: "GeeksforGeeks"})
next();
})

app.get('/', function(req, res){


console.log("User Page")
res.end();
});

app.listen(PORT, function(err){
if (err) console.log(err);
console.log("Server listening on PORT", PORT);
});

Run index.js file using below command:

node index.js

Now open a browser and go to http://localhost:3000/, now on your screen you will
see the following output:

{"title":"GeeksforGeeks"}

And you will see the following output on your console:

User Page

36

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy