Nothing Special   »   [go: up one dir, main page]

Unit 2

Download as pdf or txt
Download as pdf or txt
You are on page 1of 36

UNIT II 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 –- Fetching JSON from Express.

INTRODUCTION TO WEB SERVERS

 A website’s content is stored and delivered with the help of a web server.
 All images, texts, videos, application data, and anything else that is needed by
the user, is delivered with the help of a web server.
 Whenever a user clicks on a link or starts a download, the web server calls for the
data from the website
 It consists of the hardware and software that is responsible for responding to
requests on the World Wide Web, with the use of hypertext transfer protocol
(HTTP) and other protocols. These requests are made by clients.

 The main thing that it is responsible for, is displaying the contents of a website
to each user who requests it. This process involves storing, processing, and
delivering data.

 The exchange of data among devices is facilitated by a web server’s hardware.


The software component of a web server controls the users’ access to the hosted
files. All systems that host websites need to have the web server software.
1
Page
Functions of a Web Server
Web servers have the following functions in general:
 Web servers store and configure all website data. This is done to protect data
from unauthorized users.
 Web servers have the prime responsibility to enable accessibility to hosted
websites. This includes the availability of back-end database server services and
more.
 When potential clients around the globe are trying to access your website, your
website’s web server would serve them accordingly. Such potential clients and
visitors are known as end users and their access requests are known as end-user
requests.
 Web servers help in controlling the bandwidth; they are equipped to minimize
excess network traffic, thus regulating the overall traffic in the network. This
feature of web servers prevents downtime to a great extent. Downtime is usually
caused by surplus web traffic.
 The presence of a web server enables the creation of dynamic web pages in
popular scripting languages such as Perl, Ruby, Python, and others.

How Does a Web Server Work?

2
Page
A web browser uses HTTP to request a file hosted on a web server. The HTTP server
accepts this request, finds the file, and then sends it back to the browser using HTTP. Let
us take a look at all the steps involved in the process:
 A user specifies the URL they want to access in the address bar.
 The browser fetches the IP address of the domain name. This would take the web
browser to the web server.
 The browser requests the file from the web server using HTTP.
 The web server will send back the requested file via HTTP. If, in case, the file
does not exist, an error message will be sent.
 The browser displays the web page.

Web Server vs Application Server

S. No. Web Server Application Server


1. Web servers are bound only to web Application servers are bound to web
containers containers as well as EJB containers
2. Web servers are best-suited for Application servers are best-suited for
static content dynamic content
3. Web servers do not use a lot of Application servers use a lot of resources
resources
4. Web servers are responsible for Application servers are responsible for
arranging the run environment for arranging the run environment for
web applications enterprise applications
5. Multithreading is not supported in Multithreading is supported in
web servers application servers
6. The capacity of a web server is The capacity of an application server is
lower than that of an application more than that of a web server
server
7. The protocols used in web servers The protocols used in application servers
are HTTP and HTML are GUI, HTTP, RPC, and RMI

Examples of Web Server Uses


Web servers are a component of a larger internet and intranet package. They can be used
for:
3
Page

 Sending and receiving emails


 Downloading requests for file transfer protocol (FTP) files
 Building and publishing web pages
Server-side scripting is also supported on a lot of web servers. It employs scripts on a
web server and can help personalize the response for the clients. The server machine is
used to run server-side scripting. The process uses various scripting languages such as
Hypertext Preprocessor (PHP), Active Server Pages (ASP), etc. HTML documents can
be created dynamically by using the same process.

Types of Web Servers


Apache
Launched in 1996 and is currently maintained by the Apache Foundation, Apache Web
Server is one of the most popular web servers in the world today. It is a freeware. It is
one of the top web server examples to be compatible with platforms such as Linux,
Windows, Mac, and more.
IIS
Known widely with its abbreviation, Internet Information Services (IIS) is a web server
that is owned by Microsoft. IIS comes with the Windows Server Operating System and
can be configured via a graphic interface.
NGINX
NGINX was developed in 2002 by Igor Sysoev. It is a web server that works as a proxy
server as well. This means that it, just like Apache, can work along with another web
server. Its primary job is to handle hundreds of concurrent connections.
Apache Tomcat
Apache Tomcat is a free web server that specializes in Java Servlets. Apache Tomcat is
popularly known as a Java container. It can work under Port 8080 and supports PHP,
ASP.net, Perl, Python, and more.
LIGHTTPD
lighttpd was developed in 2003. This web server requires low memory and CPU and
disk space. Web cameras, internet routers, and other things of a similar nature use
lighttpd as their web server.

Static Web Server vs Dynamic Web Server


A static web server has a computer along with an HTTP software. When the server sends
the hosted files to the browser, they are sent without any changes.
4

On the other hand, a dynamic web server has a computer and other software such as a
Page
database and an application server. The application server can update the hosted files at
any time before they are sent to the browser. This web server can also generate content
whenever it is requested from the database. This provides flexibility but also makes the
process more complex.

Web Server Security


It is very important to keep your web server secure. With the absence of web server
security, your web server is vulnerable to various attacks such as DoS attacks, SSoS
attacks, SQL injections, unpatched software, cross-site scripting, and much more.
We can protect your web server in the following ways:
 Keep only required services on your server. Having too many services on your
web server can open portals. This can enable hacking activities in the long run.
An additional benefit of removing unnecessary services is that it will improve the
overall website functionality.
 By having separate environments for development, testing, and production, you
can reduce the risk of breach. Preferably, separate environments should be kept
private.
 Automate backups and install a firewall. A firewall will come in handy even if
all your security systems are compromised. By automating backup daily, you can
preserve data for the long run. This will be useful even when your system is
compromised beyond repair.

5
Page
JAVASCRIPT IN THE DESKTOP WITH NODEJS

Desktop applications are software programs run locally on computer devices. They
aren’t accessible from a browser, like web-based apps, and require deployment on a
personal computer or laptop.

3 Reasons Why Enterprises Use Desktop Applications


All things considered, why do enterprises often opt for desktop applications?
1. Independent of network connectivity
First off, it’s independence. All your internal procedures and customer-facing business
processes can be seriously affected by an interrupted internet connection when you use
web-based apps. With desktop software, you aren’t exposed to situations that you can’t
control.
2. Privacy, security, and other compliance-related issues
6

Desktop software is more reliable than web SaaS apps. You have total control over your
Page

desktop applications since they aren’t exposed on the web.


It’s safer to keep confidential business information and customer data on your own
server. Content stored in the cloud can easily be hacked and leaked to the web, but files
saved on your PC cannot. If you want to reduce the risk of security threats, you should
definitely consider using desktop applications.
3. Performance
Lastly, desktop apps are just faster. Quality desktop software combined with a powerful
device is capable of performing more complex tasks in a shorter time than web-based
apps. Financial operations, rendering, and trading — these are just a few examples of
the processes only desktop applications can handle effectively. Speaking of which, let’s
move on to the most common use cases of desktop software.
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
 Node.js is a runtime environment that allows you to run JavaScript on the
backend.
 A runtime environment is like a small operating system. It provides all the
functionality needed for a program to run. Node came on the scene because
JavaScript used to only work in the web browser. This is because browsers
contain an engine to translate JavaScript into code the machine understands.
 Originally the backend (i.e. data layer of an application) doesn’t have this engine.
That’s where Node.js comes in. It acts as a JavaScript engine that translates your
code, allowing it to be run on a physical machine.
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:
7

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


Page
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"
Download Node.js
The official Node.js website has installation instructions for Node.js: https://nodejs.org

Create a Node.js file named "myfirst.js", and add the following code:

myfirst.js

var http = require('http');

http.createServer(function (req, res) {


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

Save the file on your computer: C:\Users\Your Name\myfirst.js

The code tells the computer to write "Hello World!" if anyone (e.g. a web
browser) tries to access your computer on port 8080.

Navigate to the folder that contains the file "myfirst.js", the command line
interface window should look something like this:
8
Page

C:\Users\Your Name>_
Initiate the Node.js File
The file you have just created must be initiated by Node.js before any action can take
place.

Start your command line interface, write node myfirst.js and hit enter:
Initiate "myfirst.js":

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


Now, your computer works as a server!
If anyone tries to access your computer on port 8080, they will get a "Hello World!"
message in return!

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

Create a module that returns the current date and time:


9
Page

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"

How to use Node.js to build on-premise desktop apps

Though Node.js is known for being a server-side platform, interest in using it for
building desktop applications is growing rapidly. However, one of the advantages of
using Node.js for web development is the ability to use the same language on both the
server and client. JavaScript-based framework Node.js over Java for this
purpose.
Why build Node.js desktop applications?
 The ability to support multiple OSs but write the software in a common and
popular language has lots of pros because, as mentioned, desktop computing is
still a major part of how people use computers today, even as new mobile
computing platformsemerge. That’s why Node.js desktop apps have become an
interesting way to deliversoftware
 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:
1. Don’t require internet access to start and run the app.
2. Desktop apps start instantly, without having to wait for resources to download
from the internet.
3. Desktop apps have access to the computer’s OS and hardware resources,
including access to the files and folder on the user’s computer.
4. 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.
5. 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.
10

6. 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
Page
GTK. For some developers, that can be a barrier to entry and may discourage
them from considering the possibility of building a desktop app.
7. 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

Using Node.js instead of Java


1. Developer velocity. To create a new Node.js server-side application, you only
need to write about 10 lines of code. Check out the web server example on the
front page of the Node.js website for a simple, fully functional example. You can
also create a REST-based server application using freely available modules, such
as Express. Any time you need to make a change, you just restart the application,
with no compilation required. In addition, the front end of the application is also
in JavaScript. That's a good thing because having everything in the same
language boosts velocity. The coding styles are the same, the developer doesn't
need to switch programming methods or languages, and you can reuse some code,
such as third-party libraries.
2. Runtime environment. Node.js enables JavaScript programming for the server.
That means that most of the bootstrapping work you need to do to develop a
server application requires little overhead. However, you'll still need to choose
which framework to use (that is, Express, Hapi, Koa, etc.). You can find many
blog posts about which one is better based on performance, velocity, usability,
and so on. But ultimately, the choice comes down to the developer's personal
preference.
System resource utilization. Node.js is lightweight, using around 20 MB of memory
and very little processing power. Because JavaScript is asynchronous, it can hand off
the low-level work to the underlying operating system, while the application itself can
handle more requests. This means that many processes can happily run in parallel on the
same machine without hogging too many resources. Nevertheless, you should make sure
that the Node.js application isn't used to run CPU-intensive tasks. Node.js lives and dies
on maximizing its extremely fast I/O capabilities, but because it's single threaded, the
moment the CPU utilization increases all other requests begin to queue up. For
developers coming from a multi-threaded environment, this is an extremely sensitive
11

point.Advantages in all three areas:


Page
Node.js for the enterprise
 Many case studies have demonstrated the value of Node.js in the enterprise.
However, almost all these stories have one thing in common: the applications are
kept under tight control in a cloud-based or SaaS environment, where DevOps
teams can constantly monitor, debug, refactor, and update them to ensure they
always run smoothly.
 Companies such as PayPal, Walmart, and Dow Jones serve millions of requests
per day through their Node-based applications. If something goes wrong, issues
can be mitigated smoothly, with little impact on their customers.
For an on-premise solution, however, developers have none of these luxuries. After
installing software on customers' machines, developers need in-depth, precise
information in order to understand how the application is performing. Performance can
manifest itself in several different ways:

1. Application crashes. When your application goes down, the customer will contact
support and expect a prompt solution with minimal disruption. To understand the
issues, developers normally need several files, including log files, heap dumps,
and audits.
2. Performance monitoring. A bug that affects performance can be even worse than
sporadic crashes. You need a way for developers to determine why the
application is performing as it is so they can provide a solution.
3. Bugs. When customers encounter a critical bug, they report it to support, which
passes it on to the developer, along with an expectation of a quick fix by way of
a patch or new release. Unlike SaaS-based applications, however, there's no easy
way to roll back to a previous release.
4. Security and licensing. This one is more of an issue for software providers than
for the customer, but JavaScript doesn't let you protect intellectual property in the
code. Minification and obfuscation can only do so much, and they can be reverse-
engineered. Developers must ensure that the software is legally protected so
intellectual property isn't easily compromised.
When developing in Node.js, these and other problems need to be carefully thought
through. There's no compilation with JavaScript, so full testing is necessary. For
example, something as simple as misspelling a function name won't be caught until you
run the code. Extensive automated testing can mitigate this, however. Also, logging
needs to be extremely thorough so developers can determine the true problem.
Despite all these caveats and potential pitfalls, Node.js was the right technology for what
12

we wanted to achieve. Developer velocity is one of the most important factors in the era
Page

of agile programming and continuous delivery, and with Node.js our velocity increased
significantly.
Another huge benefit of coding in Node.js, and in JavaScript in general, is that
developers spend all their time actually writing and testing code, rather than having to
wait for the codebase to compile first. Most of the work we needed to do was ultimately
suited for asynchronous, I/O-based, single-threaded processes. Our developers are now
able to switch from client to server development smoothly.

But, about our intellectual property being stolen, and we minimize this by coding our
most secret algorithms in C++. But the rest of the code enjoys the convenience and
flexibility of Node.js, which was the right decision for us.

Node Framework

A framework is a collection of various libraries and tools that are required in the
development process of a software application. It acts as a base on which different
software applications can be developed. 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 and functionalities
further.

Benefits of Node Framework

 Productivity
 Scalability
 Speed
 Same Languages for Front-end and Back-end

 Maintaining Code standards across a team

Node.js Frameworks:

 Express.js: It is a fast, robust and asynchronous Model-View-Controller


framework for Node.js. It helps to direct server and routes. It helps to design
various web applications and based on passing arguments to templates. It
allows us to dynamically render HTML Pages. We use Express.js because of
its fast-track and high-speed I/O, nonparallel and single-threaded nature,
MVC like structure and its Robust API that makes routing easy. Some of the
popular frameworks are built on Express.js additionally.
 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
13

AdonisJS is that it contains a number of test modules that help to improve


Page

the efficiency of one’s code.


 MeteorJS: It is an open-source Node.js web framework. It is responsible for
producing cross-platform codes and for rapid prototyping as well. It can be
used with its own templating engine or with any other framework as well.
 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).
 SailsJS: It is built using Node.js as a base and is a MVC based framework.
It is designed from a point of view of making it easier to build customized
web applications and API’s.
 Hapi.js: It is an open-source, stable and constant Model-View-Controller
MVC framework for structuring web applications and services. Hapi.js
provides an effortless structuring of API (application programming interface)
servers, websites, and HTTP(Hypertext Transfer Protocol) proxy
applications. Because of its robust plugin system. It enables you to add new
features and fix bugs at a swift pace. Hapi.js provides you with the features
of routing, input, output validation, and caching that assists in structuring
REST APIs. It’s easy to build an API that serves clients’ needs for mobile
and single-page applications.
 Loopback.io: LoopBack is a profoundly-extensible Node.js framework that
facilitates developers to easily set up models and build powerful end-to-end
REST APIs in a matter of no time that involves minimal coding. It promotes
secure authentication and permission settings and also appears with model
relation maintenance, add-on segments, numerous backend data stores,
and Ad-hoc queries.
 Feathers.js: It is a simplistic real-time framework mounted on the top of
Express.js for writing advanced web applications. It effortlessly combines
with any client-side framework. With the help of Feathers framework, you will
discover and acquire all the modern coding protocols by default. It has a fully
customizable feature that allows Building robust lightweight web applications
real quick. As a result of the external plugin, it enables you to execute SMS,
authentications, and email messaging.
 MEAN.JS: It is a combination of open source technologies that implement
an end-to-end framework for developing dynamic web applications from the
ground up. 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.
 KoaJS: It is a recently built web framework designed by the same team that
developed Express. Its applications include a set of middleware functions
that may include certain methods for the purpose of carrying out tasks like
cache freshness, proxy support, etc.
14
Page
NPM

npm is the world's largest Software Library (Registry)


npm is also a software Package Manager and Installer
1. npm stands for Node Package Manager. It’s a library and registry for JavaScript
software packages.
2. npm also has command-line tools to help you install the different packages and
manage their dependencies.
3. an online repository for the publishing of open-source Node.js projects
4. a command-line utility for interacting with said repository helping with installing
packages and managing package versions and dependencies
Installing npm
 npm is installed with Node.js
 This means that you have to install Node.js to get npm installed on your
computer.
 Download Node.js from the official Node.js web site: https://nodejs.org
Software Package Manager
 The name npm (Node Package Manager) stems from when npm first was
created as a package manager for Node.js.
 All npm packages are defined in files called package.json.
 The content of package.json must be written in JSON.
 At least two fields must be present in the definition file: name and version.
{
"name" : "foo",
"version" : "1.2.3",
"description" : "A package for fooing things",
"main" : "foo.js",
"keywords" : ["foo", "fool", "foolish"],
"author" : "John Doe",
"licence" : "ISC"
}

Managing Dependencies
npm can manage dependencies.
npm can (in one command line) install all the dependencies of a project.
15

Dependencies are also defined in package.json.


Page
Publishing a Package
We can publish any directory from our computer as long as the directory has
a package.json file.
Check if npm is installed:
C:\>npm

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:

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

Add an HTTP Header

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:
16

var http = require('http');


Page

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

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
17
Page
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:

var http = require('http');


var fs = require('fs');
http.createServer(function (req, res) {
fs.readFile('demofile1.html', function(err, data) {
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:
18

Initiate demo_readfile.js:
Page

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


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:

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:

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!');
});

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:

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!');
});
19
Page

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:

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:

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:

Delete "mynewfile2.txt":

var fs = require('fs');

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


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

Rename Files
20

To rename a file with the File System module, use the fs.rename() method.
Page
The fs.rename() method renames the specified file:

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!');
});

21
Page
INTRODUCTION TO THE EXPRESS FRAMEWORK

o Express is a small framework that sits on top of Node.js’s web server functionality
to simplify its APIs and add helpful new features.
o It makes it easier to organize our application’s functionality with middle ware and
routing
o It adds helpful utilities to Node.js’s HTTP objects
o It facilitates the rendering of dynamic HTTP objects.
o Express is a part of MEAN stack, a full-stack JavaScript solution used in building
fast, robust, and maintainable production web applications.
o MongoDB(Database)
o ExpressJS(Web Framework)
o AngularJS(Front-end Framework)
o NodeJS(Application Server)

Installing Express on Windows

Assuming that we have installed node.js on your system, the following steps should be
followed to install express on your Windows:
STEP-1: Creating a directory for our project and make that our working directory.
$ mkdir gfg
$ cd gfg
STEP-2: Using npm init command to create a package.json file for our project.
$ npm init
This command describes all the dependencies of our project. The file will be updated
when adding further dependencies during the development process, for example when
you set up your build system.
Keep pressing enter and enter “yes/no” accordingly at the terminus line.

STEP-3: Installing Express


Now in your gfg(name of your folder) folder type the following command line:
$ npm install express --save
NOTE- Here “WARN” indicates the fields that must be entered in STEP-2.
he above command saves the installation locally in the node_modules directory and
creates a directory express inside node_modules. You should install the following
22

important modules along with express −


Page
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
STEP-4: Verify that Express.js was installed on Windows:
To check that express.js was installed on your system or not, you can run the following
command line on cmd:
C:\Users\Admin\gfg\node_modules>npm --version express
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
23

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


Page

})
Save the above code in a file named server.js and run it with the following command.
$ node server.js
will see the output −
Example app listening at http://0.0.0.0:8081
Open http://127.0.0.1:8081/ in any browser to see the result.

Request & Response

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.
We can print req and res objects which provide a lot of information related to HTTP
request and response including cookies, sessions, URL, etc.

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).
var express = require('express');
var app = express();
24

// This responds with "Hello World" on the homepage


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

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

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


})
Example app listening at http://0.0.0.0:8081
We 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
25
Page
Serving Static Files
Express provides a built-in middleware express.static to serve static files, such as images,
CSS, JavaScript, etc.
You simply need to pass the name of the directory where you keep your static assets, to
the express.static middleware to start serving the files directly. For example, if you keep
your images, CSS, and JavaScript files in a directory named public, you can do this −
app.use(express.static('public'));
We will keep a few images in public/images sub-directory as follows −
node_modules
server.js
public/
public/images
public/images/logo.png
Hello Word" app to add the functionality to handle static files.
26
Page
var express = require('express');
var app = express();
app.use(express.static('public'));
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)
})

GET Method

which passes two values using HTML FORM GET method. We are going to
use process_get router inside server.js to handle this input.

<html>

<body>

<form action = "http://127.0.0.1:8081/process_get" method = "GET">

First Name: <input type = "text" name = "first_name"> <br>

Last Name: <input type = "text" name = "last_name">

<input type = "submit" value = "Submit">

</form>

</body></html>

Let's save above code in index.htm and modify server.js to handle home page requests as
well as the input sent by the HTML form
var express = require('express');
var app = express();

app.use(express.static('public'));
app.get('/index.htm', function (req, res) {
27

res.sendFile( __dirname + "/" + "index.htm" );


Page
})

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


// Prepare output in JSON format
response = {
first_name:req.query.first_name,
last_name:req.query.last_name
};
console.log(response);
res.end(JSON.stringify(response));
})

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)


})

Accessing the HTML document using http://127.0.0.1:8081/index.htm will generate the


following form

First Name:

Last Name:

Bottom of Form

Now you can enter the First and Last Name and then click submit button to see the result
and it should return the following result −
{"first_name":"John","last_name":"Paul"}
28
Page
SERVER SIDE RENDERING WITH TEMPLATING ENGINES

o Server-side rendering (SSR) is a popular technique for rendering a normally


client-side-only single-page app (SPA) on the server and then sending a fully
rendered page to the client.
o The client’s JavaScript bundle can then take over and the SPA can operate as
normal.
SSR technique is helpful in situations where the client has a slow internet
connection and then rendering of the whole page on the client-side takes too much
time in certain situations
o Server Side Rendering might come as handy. One of the widely used modules
used to do Server Side Rendering in Node.js is EJS Module. EJS stands
for Embedded JavaScript template.

Feature of EJS Module:


 Use plain javascript.
 Fast Development time.
 Simple syntax.
 Faster execution.
 Easy Debugging.
 Active Development.

Installation of request module:


First of all, install express js and ejs using npm install.
npm install ejs
The require() method is used to load and cache JavaScript modules.
const ejs = require('ejs');
The next step is to create a folder and add a file name app.js and a file named index.ejs.
Be careful, about the syntax of the index file, here it is ejs which denotes it is an ejs file.
To run this file You need the following command.
node app.js

Render file using EJS renderFIle() method

To perform Server Side Rendering we use renderFile() method of the ejs module, which
helps us to render the ejs file on the server side.
Syntax:

ejs.renderFile( fileName, { }, { }, callback);

Here, the callback function takes two arguments first is an error (if there is an
error that occurs then the renderfile returns an error), and on successful
29

rendering it returns a template.


Page
Folder Structure:

Filename: app.js

// Requiring modules

const express = require('express');

const app = express();

const ejs = require('ejs');

const fs = require('fs');

const port = 8000;

// Render index.ejs file

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

// Render page using renderFile method

ejs.renderFile('index.ejs', {},

{}, function (err, template) {

if (err) {

throw err;
30
Page
} else {

res.end(template);

});

});

// Server setup

app.listen(port, function (error) {

if (error)

throw error;

else

console.log("Server is running");

});

Filename: index.ejs

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<meta name="viewport" content="width=device-width, initial-scale=1.0">


31
Page
</head>

<body>

<h1>Hello World</h1>

</body> </html>

Steps to run the program:


Make sure you have installed the express and request module using the
following commands:
npm install express
npm install ejs
Run app.js using the below command:
node app.js

Starting Node Server

Now type localhost:8000 in your browser to display the ejs page to see the
below result:
32
Page
Template Engines for Node.js

 Template engine helps us to create an HTML template with minimal code.


Also, it can inject data into HTML template at client side and produce the
final HTML.

 The following figure illustrates how template engine works in Node.js.

33
Page
 As per the above figure, client-side browser loads HTML template,
JSON/XML data and template engine library from the server. Template
engine produces the final HTML using template and data in client's
browser. However, some HTML templates process data and generate final
HTML page at server side also.

 There are many template engines available for Node.js. Each template
engine uses a different language to define HTML template and inject data
into it.

The following is a list of important (but not limited) template engines for
Node.js

 Jade
 Vash
 EJS
 Mustache
 Dust.js
 Nunjucks
 Handlebars
 atpl
 haml

Advantages of Template engine in Node.js

1. Improves developer's productivity.

2. Improves readability and maintainability.

3. Faster performance.

4. Maximizes client side processing.

5. Single template for multiple pages.

6. Templates can be accessed from CDN (Content Delivery Network). 34


Page
FETCHING JSON FROM EXPRESS

json() is a built-in middleware function in Express. This method is used to


parse the incoming requests with JSON payloads and is based upon the
bodyparser. This method returns the middleware that only parses JSON and
only looks at the requests where the content-type header matches the type
option.

Syntax

express.json([options])

Parameters

Following are the different options available with this method

options

inflate – This enables or disables the handling of the deflated or compressed bodies.
Default: true
limit – This controls the maximum size of the request body.
reviver – This option is passed to the JSON.parse method as the second argument.
strict – This enables or disables the accepting arrays or objects.
type – This determines the media type for the middleware that will be parsed.

Example

Create a file with the name "express.js" and copy the following code snippet.
After creating the file, use the command "node express.js" to run this code.

// express.json() Demo Example

// Importing the express module


var express = require('express');

// Initializing the express and port number


var app = express();
35

var PORT = 3000;


Page
// Calling the express.json() method for parsing
app.use(express.json());

// Reading content-type
app.post('/', function (req, res) {
console.log(req.body.name)
res.end();
})

// Listening to the port


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

Before hitting the API endpoint, set the following two properties
 Set the content-type as application/json in headers.
 Pass the following body in the POST request – {"name": "welcome"}
Output
C:\home
ode>> node express.js
Server listening on PORT 3000
welcome

36
Page

You might also like