Unit 5
Unit 5
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.
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.
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
There are various installers available on https://nodejs.org/en/. The installation files are
available for Windows, Linux, Solaris, MacOS.
Step 1:
Step 2:
Step 4:
Destination Folder :
Set the Destination Folder where you want to install Node.js & Select “Next”.
“Next”
Step 5 :
Custom Setup :
Run the following command in your command prompt or Windows Powershell and test it:-
C:\Users\Admin> node –v
5.2.2 Components
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);
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
Example :
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.
The require () function will return a JavaScript type depending on what the particular module
returns.
The following example demonstrates how to use the Node.js Http module to create a web
server.
res.end(); })
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")
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.
We can create a HTTP server with the help of http.createServer() method. (Ex:testing.js)
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………
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.
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.
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.
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:
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.
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
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);
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.
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);
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 –
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!'); });
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);