ch5 Nodejs Meghna
ch5 Nodejs Meghna
js
Chapter 5
Node.js
5.6 Exercise
2 Chapter5-Node.js
FAST SCALABLE
PERFORMANCE COMMUNITY
• Following are the areas or applications where Node.js can preferred to be used:
o I/O bound Applications
o Data Streaming Applications
o Data Intensive Real-time Applications (DIRT)
o JSON APIs based Applications
o Single Page Applications
Where Not to Use Node.js?
o It is not advisable to use Node.js for CPU intensive applications.
5.1.2 Downloading Node.js
• Node.js can be downloaded from its official website
https://nodejs.org/en/download/.
• On this site click the Windows Installer button to download the latest default
version.
• The Node.js installer also includes the NPM. NPM is the package manager for the
Node JavaScript platform. It puts modules in location such that node can find
them, and use them as an when required. So generally, it is used to publish,
discover, install, and develop node programs.
Select
32/64
bit .msi
as per
your
machine
Click the Run button on the first screen to begin the installation.
Click
on the
RUN
Click
on the
NEXT
Button
Accept the
Licence
Agreement
and Click
NEXT
Button
Enter the
file location
for
installation
Click NEXT
Button
Click the
INSTALL
Button to
Start
Installation
Click the
Finish
Button to
Complete
the
Installation
5.2.2 Components
• Node JS contains many components to develop, test and deploy applications.
• Following are the list of Node JS components:
o Node CLI
o NPM
o package.json
o Node Modules
o Development Tools and Frameworks
7 Chapter5-Node.js
5.2.2.2 NPM
NPM stands for Node Package Manager. NPM is used to install, update, uninstall and
configure Node JS modules/packages very easily.
When we install Node JS Base Platform, it installs only few components, modules and
libraries like Node CLI, NPM etc. Later on, we can use NPM to upgrade Node JS with
our required modules.
To check npm version, run “npm -v command on Node CLI :.
8 Chapter5-Node.js
5.2.2.3 package.json
“package.json” is a plain text file in JSON format. It is used to manage our application
required module dependencies. We should place this file in our application root
folder.
It defines information like our application name, module dependencies, module
versions etc. This configurations file is very important and requires more time to
explain in detail. We will discuss it in detail with some examples in coming posts.
Sample package.json file;
{
"name" : "myownapp",
"version" : "1.0",
"dependencies" : {
}
}
5.2.2.4 Node Modules
Node JS is more modular platform. Each functionality is implemented by a separate
module or package. It has some core modules like npm, install, uninstall, update etc
and rest all modules are third-party modules.
When we install Node JS Platform, by default only one module is installed i.e. npm
module. We need to use “npm” command to install required modules one by one.
All Core or Default modules are installed at /lib folder as *.js files.
Node JS has thousands of modules. A full list of Node JS Platform’s packages or
modules can be found on the NPM website https://npmjs.org/.
5.2.2.5 Development Tools and Frameworks
Many companies have developed some tools and framework to ease and reduce the
overhead of Node JS applications since the Node JS Platform has become very
popular in developing Data-Sensitive Real-time and Network applications.
9 Chapter5-Node.js
ips When the trust proxy setting is true, this property contains an array
of IP addresses specified in the ?x-forwarded-for? request header.
originalurl Retains the original request URL, also allows to rewrite req.url for
internal routing purposes.
protocol The request protocol string, "http" or "https" when requested with
TLS. (Transport Layer Security)
query Contains a property for each query string parameter in the route.
The Response object is used to send information from server to the client. i.e. the
response object is going to client as response from the server. The methods of
Response object, res, can be accessed through a dot(.) operator as res.method().
end() Used to end the response process. It signals the server that the
response is complete.
jsonp() Used to returns the response in JSON format with JSONP support
location() Based on the path parameter, it sets the response location HTTP
header field.
links() Used to set the response's Link HTTP header field by means of
joining the links provided as properties of the parameter.
1. Core Modules
2. Local Modules(user-defined modules)
3. Third Party Modules
5.3.1 Core Modules: Node.js has many built-in modules that are part of the
platform and comes with Node.js installation. These modules can be loaded into
the program by using the require function.
Syntax:
var module = require('module_name');
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.
var http = require('http');
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/html'});
res.write(“Advanced Web Technology!');
res.end();
}).listen(3000);
Local modules are created locally in your Node.js application. You can create your
own modules, and easily include them in your applications.
The following example demonstrates how to create a user-defined module and
include it in our node.
Example:
Create a calc.js file that has the following code:
The exports keyword is used to make properties and methods available outside the
module file. Since this file provides attributes to the outer world via exports,
another file can use its exported functionality using the require() function.
Now you can include and use the module in any of your Node.js files. Let’s create a
file with name implement_calc.js
Filename: implement_calc.js
The use ./ to locate the module, that means that the module is located in the same
folder as the implement_calc.js file.
Save the code above in a file called "implement_calc.js", and initiate the file:
node implement_calc.js
Output:
Note: This module also hides functionality that is not needed outside of the module.
5.3.3 Third-party modules: Third-party modules are modules that are available
online using the Node Package Manager(NPM). These modules can be installed in
the project folder or globally. Some of the popular third-party modules are
mongoose, express, angular, and react.
Example:
• npm install express
• npm install mongoose
• npm install -g @angular/cli
14 Chapter5-Node.js
Web server is required to access the web pages of any web application. The web
server handles all the http requests coming from the web application. For example,
Apache web server is used for PHP web applications, and IIS web server is used
for ASP.NET web applications.
Node.js allows to create own web server that handle incoming HTTP requests
asynchronously. Node.js has a built-in module called HTTP. This module enables
15 Chapter5-Node.js
Node.js to send data over HTTP. The HTTP module can create an HTTP server that
listens to server ports and gives a response back to the client.
Methods:
method description
createServer() create HTTP server
writeHead() Add HTTP header to the request
createServer() is used to create HTTP server. It returns an HTTP Server object. This
method includes a request object, which is used to obtain information about the
current HTTP request, such as request header, the url, and data.
Syntax
http.createServer([options][, requestListener]);
(i) options:
5.4.1.2writeHead() method:
writeHead() method write a header to the response. It is also used to specify the
status code and the content type.
Syntax:
where
status_code: It is a 3-digit HTTP status code. For example, 404 for file not found,
200 for ok, 505 for Internal Server Error.
status_message: It is string that represents the status message
headers: It takes any function, string or array.
Return value: It returns a reference to the ServerResponse, so that calls can be
chained
For example: Following code set content header. Here, first argument is status
code 200, means all is "ok". Second argument is object which represent type of
contain.
The following example demonstrates how to use Node.js http module to create a web
server. This code creates a server that will listen on port number 8000. If a browser
request is made on this port number, the server will respond to the client. The
function passed in the createServer() will be executed when the client visit the url
http://localhost:8000
{
// code // write code here
}
);
server.listen(8000); //Listen to port number 8000
Example: The following code create web server and display message "'My first js
application'" in browser.
Output :
18 Chapter5-Node.js
Query strings are appended to the end of a URL followed by ?. The query string
contains parameters in the form of a key-value pair. The key-value pare is separated
by the equal (=) symbol. The ampersand (&) symbol separates each parameter.
For example,
The function, which is passed into the createServer(), has first argument as request
object. This request object represents the request from the client. The Request object
is used to get information from a client and send information to server. The request
object has properties for the request query string, body, parameters, body, HTTP
headers etc.
"url" property of request object contains the portion of the url that follows the
domain name. For example, if user type https://oxford.com/userguide in browser,
then the value of url property is "/userguide"
Output:
Splitting of query string data means parse or separate query string parameter, so they
can process individually. To split query string data we need to first import "url"
module, use url.parse method and query property.
url.parse():
The url.parse() method parses a URL string. It split various elements of the URL such
as host, pathname, search keys, etc.
Syntax:
url.parse(urlString[, parseQueryString])
where,
query:
.query property: It rerun object containing a property for each query string
parameter.
Explanation:
• Script line var url = require('url') import url module and return reference to
"url" variable.
• Script line var query_data = url.parse(req.url, true).query; is important. Here,
• The Node.js file system module enables us to work with the file system on one’s
own computer.
• To include the File System module, we use the require() method as below:
var fs = require('fs');
• Every method in the ‘fs’ module has synchronous as well as asynchronous forms.
• Asynchronous methods take the last parameter as the completion function
callback and the first parameter of the callback function as error.
• It is better to use an asynchronous method instead of a synchronous method,
• As the asynchronous method never blocks a program during its execution,
whereas the second one does.
• Some common uses of ‘fs’ module are:
o Read Files
o Create Files
o Update Files
o Delete Files
o Rename Files
• To demonstrate the above uses let us first create a simple text file and save it as
test.txt. Consider that the test.txt has following content:
This is a test file for demonstrating the use of different uses of file system modules
of node js in the book Advanced Web Technology!!
5.5.1 Read Files
• The fs.readFile() method is used to read files on one’s own computer.
• Let us create a js file named read_demo.js with the following code:
var fs = require("fs");
// Asynchronous read
fs.readFile('test.txt', function (err, data) {
if (err) {
return console.error(err);
}
console.log("Asynchronous read: " + data.toString());
});
// Synchronous read
var data = fs.readFileSync(test.txt');
console.log("Synchronous read: " + data.toString());
console.log("Program Completed");
• Output:
22 Chapter5-Node.js
r Reading.
w Writing. The file is created (if it does not exist) or truncated (if it exists).
w+ Reading and writing. The file is created (if it does not exist) or truncated
23 Chapter5-Node.js
• Example
The following code shows how to open a file test.txt for reading and writing.
Save this file as open_demo.js.
var fs = require("fs");
$ node open_demo.js
• Output:
• fs.writeFile() method is used to create a new file if it does not exist. It will
over-write the file if the file already exists.
• Syntax:
fs.writeFile(filename, data[, options], callback)
The following code shows how to create and write in new file named
test2.txt for reading and writing. Save this file as write_demo.js.
var fs = require("fs");
console.log("Trying to write in a new file");
fs.writeFile('test2.txt', 'Easy Learning! With Advanced Web Technology!
book', function(err) {
if (err) {
return console.error(err);
}
console.log("Data written successfully!");
console.log("Let's read newly written data");
fs.readFile('test2.txt', function (err, data) {
if (err) {
return console.error(err);
}
console.log("Asynchronous read: " + data.toString());
});
});
• Output:
• fs.appendFile() method is also used to create a new file if it does not exist.
It will append the content in the file if it already exists.
• Syntax:
fs.appendFile(filename, data[, options], callback)
var fs = require("fs");
console.log("Trying to create a new file with appenFile() method of File
System");
fs.appendFile('test3.txt', ‘Advanced Web Technology book by Oxford! ',
function(err) {
if (err) {
return console.error(err);
25 Chapter5-Node.js
}
console.log("Data written using append method successfully!");
console.log("Let's read newly written data");
fs.readFile('test3.txt', function (err, data) {
if (err) {
return console.error(err);
}
console.log("Asynchronous read: " + data.toString());
});
});
• Output:
var fs = require("fs");
console.log("Trying to update an existing file with appenFile() method of
File System");
fs.appendFile('test3.txt', ‘Very Informative and Good Book! ',
function(err) {
if (err) {
return console.error(err);
}
console.log("Data appended using append method successfully!");
console.log("Let's read newly updated data");
fs.readFile('test3.txt', function (err, data) {
if (err) {
return console.error(err);
}
console.log("Asynchronous read: " + data.toString());
});
});
• Output:
26 Chapter5-Node.js
• The fs.writeFile() method replaces the specified file and its content.
• Example:
• The following code overwrites the content of the file "text3.txt". Save this file
as write2update_demo.js.
var fs = require("fs");
console.log("Trying to overwrite an existing file with writeFile() method
of File System");
fs.writeFile('test3.txt', ‘New Overwritten text! ', function(err) {
if (err) {
return console.error(err);
}
console.log("Data overwrite using write method successfully!");
console.log("Let's read newly overwritten data of same file");
fs.readFile('test3.txt', function (err, data) {
if (err) {
return console.error(err);
}
console.log("Asynchronous read: " + data.toString());
});
});
• Output:
• The File System module has unlink() method for deleting files.
• Syntax:
fs.unlink(path, callback)
}
console.log("File deleted successfully!");
});
• Output:
5.6 Exercise
A) Choose the correct option from following MCQs:
1. In which of the following areas, Node.js is absolutely perfect to use?
A. I/O bound Applications
28 Chapter5-Node.js
B) Answer in brief:
1. Define npm
6. Name few tools and frameworks developed over Node JS to make it more
easier to use.
C) Answer in detail:
4. List and explain few methods of request and response objects of http.