Unit 2
Unit 2
Unit 2
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.
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.
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.
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.
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.
Desktop software is more reliable than web SaaS apps. You have total control over your
Page
Create a Node.js file named "myfirst.js", and add the following code:
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":
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:
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"
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
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.
Productivity
Scalability
Speed
Same Languages for Front-end and Back-end
Node.js Frameworks:
Managing Dependencies
npm can manage dependencies.
npm can (in one command line) install all the dependencies of a project.
15
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');
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:
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
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.
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
Save the code above in a file called "demo_http_url.js" and initiate the file:
Initiate 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
http://localhost:8080/winter
/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:
Save the code above in a file called "demo_readfile.js", and initiate the file:
18
Initiate demo_readfile.js:
Page
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:
var fs = require('fs');
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:
var fs = require('fs');
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:
var fs = require('fs');
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:
var fs = require('fs');
var fs = require('fs');
Delete Files
To delete a file with the File System module, use the fs.unlink() method.
Delete "mynewfile2.txt":
var fs = require('fs');
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:
var fs = require('fs');
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)
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.
})
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.
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
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>
</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
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
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:
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
Filename: app.js
// Requiring modules
const fs = require('fs');
ejs.renderFile('index.ejs', {},
if (err) {
throw err;
30
Page
} else {
res.end(template);
});
});
// Server setup
if (error)
throw error;
else
console.log("Server is running");
});
Filename: index.ejs
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<body>
<h1>Hello World</h1>
</body> </html>
Now type localhost:8000 in your browser to display the ejs page to see the
below result:
32
Page
Template Engines for 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
3. Faster performance.
Syntax
express.json([options])
Parameters
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.
// Reading content-type
app.post('/', function (req, res) {
console.log(req.body.name)
res.end();
})
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