0% found this document useful (0 votes)
11 views18 pages

Unit 5

Uploaded by

bitestkaran
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
11 views18 pages

Unit 5

Uploaded by

bitestkaran
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 18

5.

1 Concepts, working and Features

Concepts

Node.js is an open source, cross-platform runtime environment for developing server-side and
networking applications. Node.js applications are written in JavaScript, and can be run within
the Node.js runtime on OS X, Microsoft Windows, and Linux.

Node.js also provides a rich library of various JavaScript modules which simplifies the
development of web applications using Node.js to a great extent.

Node.js = Runtime Environment + JavaScript Library

working

Node.js accepts the request from the clients and sends the response, while working with the
request node.js handles them with a single thread. To operate I/O operations or requests
node.js use the concept of threads. Thread is a sequence of instructions that the server
needs to perform. It runs parallel on the server to provide the information to multiple
clients. Node.js is an event loop single-threaded language. It can handle concurrent requests
with a single thread without blocking it for one request.
Node.js basically works on two concept :
 Asynchronous - Asynchronous is executing a callback function. The moment we get the
response from the other server or database it will execute a callback function. Callback
functions are called as soon as some work is finished and this is because the node.js uses
an event-driven architecture.
 Non-blocking I/O - Non-blocking i/o means working with multiple requests without
blocking the thread for a single request.

Features

 Asynchronous and Event Driven − All APIs of Node.js library are asynchronous, that is,
non-blocking. It essentially means a Node.js based server never waits for an API to
return data. The server moves to the next API after calling it and a notification
mechanism of Events of Node.js helps the server to get a response from the previous
API call.
 Very Fast − Being built on Google Chrome's V8 JavaScript Engine, Node.js library is very
fast in code execution.

Web Design-II Page 1


 Single Threaded but Highly Scalable − Node.js uses a single threaded model with event
looping. Event mechanism helps the server to respond in a non-blocking way and makes
the server highly scalable as opposed to traditional servers which create limited threads
to handle requests. Node.js uses a single threaded program and the same program can
provide service to a much larger number of requests than traditional servers like Apache
HTTP Server.
 No Buffering − Node.js applica ons never buffer any data. These applica ons simply
output the data in chunks.
 License − Node.js is released under the MIT (Massachusetts Institute of Technology)
license. (Users of software using an MIT License are permitted to use, copy, modify,
merge publish, distribute, sublicense and sell copies of the software.)

5.1.1 Downloading Node.js

Download latest version of Node.js installable archive file from Node.js Downloads. At the
time of writing this tutorial, following are the versions available on different OS.

OS Archive Name
Windows node-v6.3.1-x64.msi
Linux node-v6.3.1-linux-x86.tar.gz
Mac node-v6.3.1-darwin-x86.tar.gz
SunOS node-v6.3.1-sunos-x86.tar.gz

5.2 Setting up Node.js server(HTTP server)

5.2.1 Installing on window

There are various installers available on https://nodejs.org/en/. The installation files are
available for Windows, Linux, Solaris, MacOS.

Step 1:

Web Design-II Page 2


Downloading the Node.js ‘.msi’ installer the first step to install Node.js on Windows is to
download the installer.
staller. Visit the official Node.js website i.e) https://nodejs.org/en/download/

Step 2:

Running the Node.js installer. Double click on the .msi installer.

The Node.js Setup wizard will open.


Welcome To Node.js Setup Wizard.
Select “Next”.

Step 3: After clicking “Next”, End--User


User License Agreement (EULA) will open.
Web Design-II Page 3
Check “I accept the terms in the License Agreement”
Agreement”. Select “Next”.

Step 4:
Destination Folder :
Set the Destination Folder where you want to install Node.js & Select “Next”.
“Next”

Step 5 :
Custom Setup :

Web Design-II Page 4


Select “Next”

Ready to Install Node.js.


The installer may prompt you to “install tools for native modules”.
Select “Install”

Do not close or cancel the installer until the install is complete


Complete the Node.js Setup Wizard.
Click “Finish”.
Web Design-II Page 5
Step 3: Verify that Node.js was properly installed or not.

Run the following command in your command prompt or Windows Powershell and test it:-

C:\Users\Admin> node –v

Step 4: Updating the Local npm version.


npm install npm --global // Updates the ‘CLI’ client

5.2.2 Components

5.2.2.1 Required modules, Create Server(http.createServer())

The http.createServer() method turns your computer into an HTTP server.

The http.createServer() method creates an HTTP Server object.

The HTTP Server object can listen to ports on your computer and execute a function,
a requestListener, each time a request is made.

http.createServer(requestListener
requestListener);

Web Design-II Page 6


Parameter Description

requestListener Optional. Specifies a function to be executed every time the server gets a
request. This function is called a requestListener, and handles request from
the user, as well as response back to the user.

Technical detail

Return value : HTTP server object Node js Version 0.1.13

Example :

var http = require('http');


http.createServer(function (req, res) {
// Send the HTTP header
// HTTP Status: 200 : OK
// Content Type: text/plain
res.writeHead(200, {'Content-Type': 'text/plain'});
// Send the response body as "Hello World"
res.write('Hello World!');
res.end();
}).listen(3000);
// Console will print the message
console.log('Server running at http://127.0.0.1:3000/');

5.2.2.2 Request and response


Now write the above code in file and save the file as testing.js; while executing the above it will just create an HTTP
server which listens to the port mentioned as 3000 on the local machine.

Web Design-II Page 7


For starting the server, we need to start the command prompt as follows:

Web Design-II Page 8


Once you get the message like server is running at ….. , We can just open any browser and
check for the http://127.0.0.1:3000/ Now, if you make any changes in the " testing.js" file, you
need to again run the "node testing.js" command. This is how the http server is created and
request which are sent over https server are responded from the port 3000.

5.3 Built-in Modules

In Node.js, Modules are the blocks of encapsulated code that communicates with an external
application on the basis of their related functionality. Modules can be a single file or a
collection of multiples files/folders.

Node.js has many built-in modules that are part of the platform and comes with Node.js
installation. Node Js Core Modules comes with its installation by default. You can use them as
per application requirements.

5.3.1 require() function

The require () function will return a JavaScript type depending on what the particular module
returns.

var module = require('module_name');

The following example demonstrates how to use the Node.js Http module to create a web
server.

var http = require('http');

http.createServer(function (req, res) {

res.writeHead(200, {'Content-Type': 'text/html'});

res.write('Welcome to this page!');

res.end(); })

Web Design-II Page 9


.listen(3000);

In the above example, the require() function returns an object because the Http module
returns its functionality as an object. The function http.createServer() method will be executed
when someone tries to access the computer on port 3000. The res.writeHead() method is the
status code where 200 means it is OK, while the second argument is an object containing the
response headers.

Module Description
OS Module Provides basic operating-system related utility functions. var
os = require("os")
Path Module Provides utilities for handling and transforming file paths.
var path = require("path")
Net Module Provides both servers and clients as streams. Acts as a
network wrapper. var net = require("net")
DNS Module Provides functions to do actual DNS lookup as well as to use
underlying operating system name resolution
functionalities. var dns = require("dns")
Domain Provides ways to handle multiple different I/O operations as
Module a single group. var domain = require("domain")

5.3.2 User defined module: create and include

Modules are the collection of JavaScript codes in a separate logical file that can be used in
external applications on the basis of their related functionality. Modules are popular as they
are easy to use and are reusable.

5.3.3 HTTP module

Web Design-II Page 10


To make HTTP requests in Node.js, there is a built-in module HTTP in Node.js to transfer data
over the HTTP. To use the HTTP server in node, we need to require the HTTP module. The
HTTP module creates an HTTP server that listens to server ports and gives a response back to
the client. The HTTP core module is a key module to Node.js networking. It is designed to
support many features of the HTTP protocol.

We can create a HTTP server with the help of http.createServer() method. (Ex:testing.js)

var http = require('http');


http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/html'});
res.write('Welcome to this page!');
res.end(); })
.listen(3000);

http.METHODS
This property lists all the HTTP methods supported:
> require('http').METHODS
[ 'ACL', 'BIND', 'CHECKOUT', 'CONNECT', 'COPY', 'DELETE', 'GET', 'HEAD', 'LINK', 'LOCK', 'M-
SEARCH', 'MERGE', 'MKACTIVITY', 'MKCALENDAR', 'MKCOL', 'MOVE', 'NOTIFY', 'OPTIONS',
'PATCH', 'POST', 'PROPFIND', 'PROPPATCH', 'PURGE', 'PUT', 'REBIND', 'REPORT', 'SEARCH',
'SUBSCRIBE', 'TRACE', 'UNBIND', 'UNLINK', 'UNLOCK', 'UNSUBSCRIBE']

http.STATUS_CODES
> require('http').STATUS_CODES
{ '100': 'Continue',
'101': 'Switching Protocols',
'102': 'Processing',
'103': 'Early Hints',
'200': 'OK',
'201': 'Created',
'202': 'Accepted',
'203': 'Non-Authoritative Information',
'204': 'No Content',
'205': 'Reset Content',
'206': 'Partial Content',
Web Design-II Page 11
'207': 'Multi-Status',
'208': 'Already Reported',
'226': 'IM Used',
'300': 'Multiple Choices',
'301': 'Moved Permanently',
'302': 'Found',
'303': 'See Other',
'304': 'Not Modified',
'305': 'Use Proxy',
'307': 'Temporary Redirect',
and many more………

5.4 Node.js as Web-server:

When you view a webpage in your browser, you are making a request to another computer on
the internet, which then provides you the webpage as a response. That computer you are
talking to via the internet is a web server. A web server receives HTTP requests from a client,
like your browser, and provides an HTTP response, like an HTML page or JSON from an API. To
access web pages of any web application, you need a web server. The web server will handle
all the http requests for the web application e.g IIS is a web server for ASP.NET web
applications and Apache is a web server for PHP or Java web applications.

A lot of software is involved for a server to return a webpage. This software generally falls into
two categories: frontend and backend. Front-end code is concerned with how the content is
presented, such as the color of a navigation bar and the text styling. Back-end code is
concerned with how data is exchanged, processed, and stored. Code that handles network
requests from your browser or communicates with the database is primarily managed by back-
end code.

Node.js allows developers to use JavaScript to write back-end code, even though traditionally
it was used in the browser to write front-end code. Having both the frontend and backend
together like this reduces the effort it takes to make a web server, which is a major reason
why Node.js is a popular choice for writing back-end code.

Node.js provides capabilities to create your own web server which will handle HTTP requests
asynchronously. You can use IIS or Apache to run Node.js web application but it is
recommended to use Node.js web server.

Web Design-II Page 12


5.4.1 createServer() , writeHead() method

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. Refer the code below to understand
the concept; filename: testing.js

1. The basic functionality of the require function is that it reads a JavaScript file, executes the
file, and then proceeds to return the exports object. So in our case, since we want to use the
functionality of the http module, we use the require function to get the desired functions from
the http module so that it can be used in our application.

2. In this line of code, we are creating a server application which is based on a simple function.
This function is called whenever a request is made to our server application. The request
object can be used to get information about the current HTTP request e.g., url, request
header, and data. The response object can be used to send a response for a current HTTP
request.

3. When a request is received, we are saying to send a response with a header type of ‘200.’
This number is the normal response which is sent in an http header when a successful
response is sent to the client.

4. In the response itself, we are sending the string ‘Hello World.’

Web Design-II Page 13


5. We are then using the server.listen function to make our server application listen to client
requests on port no 8081. You can specify any available port over here.

Run the above web server by writing node testing.js command in command prompt or
terminal window and it will display message of node.js is running of port no. 8081.

5.4.2 Reading Query String, Split Query String

In Node.js, functionality to aid in the accessing of URL query string parameters is built into the
standard library. The built-in url.parse method takes care of most of the heavy lifting for us.
Here is an example script using this handy function and an explanation on how it works:

const http = require('http');


const url = require('url');
http.createServer(function (req, res) {
const queryObject = url.parse(req.url,true).query;
console.log(queryObject);
res.writeHead(200, {'Content-Type': 'text/html'});
res.end('Feel free to add query parameters to the end of the url'); }).listen(8080);

To test this code run node app.js (app.js is name of the file) on the terminal and then go to
your browser and type http://localhost:8080/app.js?foo=bad&baz=foo on the URL bar.

The key part of this whole script is this line: const queryObject = url.parse(req.url,true).query;.
Let's take a look at things from the inside-out. First off, req.url will look like
/app.js?foo=bad&baz=foo. This is the part that is in the URL bar of the browser. Next, it gets
passed to url.parse which parses out the various elements of the URL (NOTE: the second
parameter is a boolean stating whether the method should parse the query string, so we set it
to true). Finally, we access the .query property, which returns us a nice, friendly JavaScript
object with our query string data.

5.5 File System Module:


5.5.1 Read Files (readFile())

The Node.js file system module (fs module) allows you to work with the files. The fs.readFile()
is used to read from file. There are two ways to read file

1. Read file Asynchronously:


Web Design-II Page 14
var fs = require('fs');
fs.readFile('my_file.txt', (err, data) => {
if (err){ throw err; }
else{ console.log("Content of file is: " + data); } });

2. Read file Synchronously:


var fs = require('fs');
var filename = 'my_file.txt';
var content = fs.readFileSync(filename);
console.log('Content of file is: ' + content);

for ex.:
filename: readfiledemo.js
var http = require('http');
var fs = require('fs');
http.createServer(function (req, res) {
fs.readFile('summer.html', function(err, data) {
res.writeHead(200, {'Content-Type': 'text/html'});
res.write(data);
return res.end();
});
}).listen(3000);

5.5.2 Create Files(appendFile(),open(),writeFile())


There are a bunch of methods used for creating new files are: fs.appendFile (), fs.open (),
fs.writeFile (). The append method is used to, as the name suggests, append the given file.
Also, if one particular file is appended but does not exist then a file of the same name will be
created. The syntax of fs.appendFile () would look something like –

fs.appendFile('newfile.txt', 'Hello Konfinity!', function (err) {


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

Web Design-II Page 15


The next method to discuss is the fs.open() method. This method takes a "flag" as the second
argument. If the flag is "w", the specified file is opened for writing and if the called file does
not exist then an empty file is created. The syntax of the fs.open() method will look like

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


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

If you want to replace a particular file and its contents then the fs.writeFile() method is used.
Also, if the file doesn’t already exist, a new one will be created.

fs.writeFile('newfile3.txt', 'Hello Konfinity!', function (err) {


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

for ex.:
filename: appendfiledemo.js
var http = require('http');
var fs = require('fs');
http.createServer(function (req, res) {
fs.appendFile('myfile.txt','Hello, students!', function(err) {
if(err) throw err;
res.end('saved');
});
}).listen(3000);

for ex.:
filename: appendfiledemo.js
var http = require('http');
var fs = require('fs');
http.createServer(function (req, res) {
fs.appendFile('myfile1.txt','Hello! Students', function(err) {
if(err) throw err;
res.end('file is created.');
});
Web Design-II Page 16
}).listen(3000);

5.5.3 Update Files(appendFile(),writeFile())

The methods generally used to update files in a system are fs.appendFile() and fs.writeFile().
fs.appendFile() is a method that appends particular content at the end of the file mentioned in
the code. The syntax for the method fs.appendFile() would look like –

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


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

This code would append the text "This is my text." to the end of the file that goes by the name
"newfile1.txt". Another method is the fs.writeFile() one which replaces the file and content
mentioned in the code. The syntax of the method is:
fs.writeFile('mynewfile3.txt', 'This is my text', function (err) {
if (err) throw err;
console.log('Replaced!'); });

5.5.4 Delete Files(unlink())


The fs.unlink() method is used to delete a particular file with the File System module. The
syntax of this method will look like –
fs.unlink('newfile2.txt', function (err) {
if (err) throw err;
console.log ('File deleted!'); });

for ex.:
filename: deletefiledemo.js
var http = require('http');
var fs = require('fs');
http.createServer(function (req, res) {
fs.unlink('myfile1.txt', function(err) {
if(err) throw err;
res.end('file is deleted.');
});
}).listen(3000);
Web Design-II Page 17
5.5.5 Rename Files(rename())

In Nodejs, developers can also upload files to their computer. Apart from this, the file system
module can also be used to rename files. The fs.rename() method is used to rename a file. This
method renames the file mentioned in the code, the syntax for the same will look like –
fs.rename('myfile.txt', myfile1.txt', function (err) {
if (err) throw err;
console.log('File Renamed!'); });

for ex.:
filename: deletefiledemo1.js
var http = require('http');
var fs = require('fs');
http.createServer(function (req, res) {
fs.rename('myfile.txt','myfile1.txt', function(err) {
if(err) throw err;
res.end('file is changed.');
});
}).listen(3000);

Web Design-II Page 18

You might also like