Full Stack Unit 2
Full Stack Unit 2
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 server respond to the client request in either of the following two ways:
Sending the file to the client associated with the requested URL.
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
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
It is the responsibility of parent process to monitor the load and decide if processes
should be killed or forked.
Multi-threaded
Hybrid
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.
What is Node.js?
Why Node.js?
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.
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.
The app is so small that you can create the files by hand. At the bare minimum, you
only need two files:
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.
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.
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
<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?
The NPM program is installed on your computer when you install Node.js
What is a Package?
A package in Node.js contains all the files you need for a module.
Download a Package
Open the command line interface and tell NPM to download the package you want.
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.
C:\Users\My Name\node_modules\upper-case
Using a Package
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
Initiate demo_uppercase:
If you have followed the same steps on your computer, you will see the same result as
the example: http://localhost:8080
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:
Now your application has access to the HTTP module, and is able to create a server:
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
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"
Now you can include and use the module in any of your Node.js files.
Example
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:
If you have followed the same steps on your computer, you will see the same result as
the example: http://localhost:8080
Node.js has a built-in module called HTTP, which allows Node.js to transfer data over
the Hyper Text Transfer Protocol (HTTP).
The HTTP module can create an HTTP server that listens to server ports and gives a
response back to the client.
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:
If you have followed the same steps on your computer, you will see the same result as
the example: http://localhost:8080
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
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
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:
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
/summer
http://localhost:8080/winter
/winter
There are built-in modules to easily split the query string into readable parts, such as
the URL module.
Example
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
year=2017&month=July
2017 July
The Node.js file system module allows you to work with the file system on your
computer.
var fs = require('fs');
Read files
Create files
Update files
Delete files
Rename files
Read Files
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
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:
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
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:
Example
var fs = require('fs');
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
var fs = require('fs');
Update Files
fs.appendFile()
fs.writeFile()
The fs.appendFile() method appends the specified content at the end of the specified
file:
Example
var fs = require('fs');
Example
var fs = require('fs');
To delete a file with the File System module, use the fs.unlink() method.
Delete "mynewfile2.txt":
var fs = require('fs');
Rename Files
To rename a file with the File System module, use the fs.rename() method.
Example
var fs = require('fs');
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 −
Firstly, install the Express framework globally using NPM so that it can be used to
create a web application using node terminal.
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.
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.
Save the above code in a file named server.js and run it with the following command.
$ node server.js
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.
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
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.
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 #.
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:
In the same file, create a route that renders the file this way:
The render method takes the name of the file (without the extension) and then the
values of the variables in the template file.
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 %>.
Next, switch the app view engine setting from Pug to 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
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.
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:
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.
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.’);
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
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.
console.log('Before')
doSomething()
console.log('After')
31
Fetching JSON from Express
Syntax:
express.json( [options] )
Parameters: The options parameter have various property like inflate, limit, type, etc.
1. You can visit the link to Install express module. You can install this
package by using this command.
2. After installing the express module, you can check your express
version in command prompt using the command.
3. After that, you can just create a folder and add a file for example,
index.js. To run this file you need to run the following command.
node index.js
app.use(express.json());
app.listen(PORT, function(err){
if (err) console.log(err);
console.log("Server listening on PORT", PORT);
});
32
2. Make sure you have installed express module using the following
command:
npm install express
node index.js
Output:
app.listen(PORT, function(err){
if (err) console.log(err);
console.log("Server listening on PORT", PORT);
});
node index.js
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.
2. After installing the express module, you can check your express version in
command prompt using the command.
3. After that, you can just create a folder and add a file for example, index.js. To run
this file you need to run the following command.
node index.js
// 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:
node index.js
Output:
4. Now open browser and go to http://localhost:3000/, now on your screen you will
see the following output:
{"user":"geek"}
// With middleware
35
app.use('/', function(req, res, next){
res.json({title: "GeeksforGeeks"})
next();
})
app.listen(PORT, function(err){
if (err) console.log(err);
console.log("Server listening on PORT", PORT);
});
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"}
User Page
36