NodeJS UNIT-II
NodeJS UNIT-II
UNIT I
Distributed Component Architecture: Introduction- Methods of
Distribution: Sockets, RPC, DCE, RMI, CORBA, DCOM-Multi-tier Architecture
-Component Concepts- Characteristics- RMI: Basic concepts Server side
and Client side processes.
UNIT II
Introduction to Node.js- Features of Node.js – Environment Setup – REPL – NPM-
Callback Concepts Event Driven Programming-#Streams-File System# – Utility
Modules.
UNIT III
Presentation Techniques: Java Servlets – Reading Data from Client and
HTTP Request Header-Sending Data to a Client and writing the HTTP
Response Header- Working with Cookies- Tracking Sessions. Java Server
Pages- JSP Tags – Tomcat- #Session objects#.
UNIT IV
Interconnection Techniques: Java Mail API: Send Email Message-Retrieving
Email Messages- Deleting Email Messages-#Replaying and Forwarding an
Email Message#. Java Messaging Services- JMS fundamentals-
Components-Sending and Receiving Message on Ǫueue-Compiling and
running the Publisher and Subscriber.
UNIT V
Component Programming: Enterprise Java Beans - Deployment
Descriptors-Session Java Bean – Life cycle of Session Beans - Entity Java
Bean – Life cycle of Entity Bean – Message Driven Bean- Life cycle of
Message Driven Bean –#The JAR file#.
Text books:
1.G. SudhaSadasivam, Distributed Component Architecture, Wiley India
Pvt. Ltd, 2008. UNIT I : Chapter 1 – 1.1, 1.3, 1.5 & 1.6
2.Jim Keogh, J2EE-The Complete Reference, Tata McGraw Hill Education Pvt.
Ltd, 2010 UNIT I : Chapter 6 UNIT III : Chapter 10,11
UNIT IV: Chapter 13,15 and 16 UNIT V: Chapter 12
Web Reference:
UNIT II: http://www.tutorialspoint.com/nodejs/nodejs_quick_guide.htm
Book for Reference:
Richard Monson Haefel, Enterprise Java Beans, O ‘Reilly Fourth Edition, 2004
With Best
Compliments
from Dr. S.
Mohamed Iliyas
Assistant
Professor
PG & Research Department of
Computer Science Jamal
Mohamed College
(Autonomous)
Tiruchirappalli – 620 020
98946 – 48788
[email protected]
UNIT – II : Node.js
Introduction to Node.js
Node.js is a server-side platform built on Google Chrome's JavaScript Engine (V8 Engine). Node.js
was developed by Ryan Dahl in 2009 and its latest version is v0.10.36. The definition of Node.js is as
follows:
“Node.js is a platform built on Chrome's JavaScript runtime for easily building fast and scalable network
applications. Node.js uses an event-driven, non-blocking I/O model that makes it lightweight and
efficient, perfect for data-intensive real-time applications that run across distributed devices.”
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
Features of Node.js
Following are some of the important features that make Node.js the first choice of software architects.
Asynchronous and Event Driven − All APIs of Node.js library is 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.
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 applications never buffer any data. These applications simply output the
data in chunks.
License − Node.js is released under the MIT license
Following are the areas where Node.js is proving itself as a perfect technology partner.
I/O bound Applications
Data Streaming Applications
Data Intensive Real-time Applications (DIRT)
JSON APIs based Applications
Single Page Applications
Environment Setup
If we are still willing to set up your environment for Node.js, you need the following two software’s
available on your computer,
(a) Text Editor and
(b) The Node.js binary installables.
Text Editor
This will be used to type your program. Examples of few editors include Windows Notepad, OS Edit
command, Brief, Epsilon, EMACS, and vim or vi.
Name and version of text editor can vary on different operating systems. For example, Notepad will
be used on Windows, and vim or vi can be used on windows as well as Linux or UNIX.
The files you create with your editor are called source files and contain program source code. The
source files for Node.js programs are typically named with the extension ".js".
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
Installation on Windows
Use the MSI file and follow the prompts to install the Node.js. By default, the installer uses the Node.js
distribution in C:\Program Files\nodejs. The installer should set the C:\Program Files\nodejs\bin directory
in window's PATH environment variable. Restart any open command prompts for the change to take effect.
REPL Terminal
REPL stands for Read Eval Print Loop and it represents a computer environment like a Windows
console or Unix/Linux shell where a command is entered and the system responds with an output in an
interactive mode. Node.js or Node comes bundled with a REPL environment. It performs the following tasks
−
Read − Reads user's input, parses the input into JavaScript data-structure, and stores in memory.
Eval − Takes and evaluates the data structure.
Print − Prints the result.
Loop − Loops the above command until the user presses ctrl-c twice.
The REPL feature of Node is very useful in experimenting with Node.js codes and to debug JavaScript
codes.
Starting REPL
REPL can be started by simply running node on shell/console without any arguments as follows.
$ node
You will see the REPL Command prompt > where you can type any Node.js command −
$ node
>
Simple Expression
Let's try a simple mathematics at the Node.js REPL command prompt −
$ node
>1+3
4
>1+(2*3)-4
3
>
Use Variables
You can make use variables to store values and print later like any conventional script.
If var keyword is not used, then the value is stored in the variable and printed. Whereas if var keyword is
used, then the value is stored but not printed. You can print variables using console.log().
$ node
>x=
10 10
>var y = 10
Multiline Expression
Node REPL supports multiline expression similar to JavaScript. Let's check the following do-while loop in
action −
$ node
>var x =
0
undefined
> do {
... x++;
... console.log("x: " + x);
... }
while ( x<
5 ); x: 1
x: 2
x: 3
x: 4
x: 5
undefine
d
>
comes automatically when you press Enter after the opening bracket. Node automatically checks the
continuity of expressions.
Underscore Variable
You can use underscore (_) to get the last result −
$ node
>var x =
10
undefined
>var y =
20
undefined
>x+
y 30
>var sum =
_ undefined
> console.log(sum
) 30
undefined
>
REPL Commands
ctrl + c − terminate the current command.
ctrl + c twice − terminate the Node REPL.
ctrl + d − terminate the Node REPL.
Stopping REPL
As mentioned above, you will need to use ctrl-c twice to come out of Node.js REPL.
$ node
>
(^C again to quit)
>
Using package.json
package.json is present in the root directory of any Node application/module and is used to define the
properties of a package.
Attributes of Package.json
name − name of the package
version − version of the package
description − description of the package
homepage − homepage of the package
author − author of the package
contributors − name of the contributors to the package
dependencies − list of dependencies. NPM automatically installs all the dependencies
mentioned here in the node_module folder of the package.
repository − repository type and URL of the package
main − entry point of the package
keywords − keywords
Uninstalling a Module
Use the following command to uninstall a Node.js module.
$ npm uninstall express
Once NPM uninstalls the package, you can verify it by looking at the content of /node_modules/ directory or
type the following command −
$ npm ls
Updating a Module
Update package.json and change the version of the dependency to be updated and run the following
command.
$ npm update express
Create a Module
Creating a module requires package.json to be generated. Let's generate package.json using NPM, which
will generate the basic skeleton of the package.json.
$ npminit
This utility will walk you through creating a package.json file.
It only covers the most common items, and tries to guess sane defaults.
Callbacks Concept
Callback is an asynchronous equivalent for a function. A callback function is called at the
completion of a given task. Node makes heavy use of callbacks. All the APIs of Node are written in such
a way that they support callbacks.
For example, a function to read a file may start reading file and return the control to the execution
environment immediately so that the next instruction can be executed. Once file I/O is complete, it will
call the callback function while passing the callback function, the content of the file as a parameter. So
there is no blocking or wait for File I/O. This makes Node.js highly scalable, as it can process a high
number of requests without waiting for any function to return results.
This material gives self-learning content to teach the world in simple and easy way!!!!!
var fs = require("fs");
var data =
fs.readFileSync('input.txt');
console.log(data.toString());
These two examples explain the concept of blocking and non-blocking calls.
The first example shows that the program blocks until it reads the file and then only it proceeds to
end the program.
The second example shows that the program does not wait for file reading and proceeds to print
"Program Ended" and at the same time, the program without blocking continues reading the
file.
Thus, a blocking program executes very much in sequence. From the programming point of view, it is easier
to implement the logic but non-blocking programs do not execute in sequence. In case a program needs to
use any data to be processed, it should be kept within the same block to make it sequential execution.
Event-Driven Programming
Node.js uses events heavily and it is also one of the reasons why Node.js is pretty fast compared to
other similar technologies. As soon as Node starts its server, it simply initiates its variables, declares
functions and then simply waits for the event to occur.
In an event-driven application, there is generally a main loop that listens for events, and then triggers
a callback function when one of those events is detected.
Example
Create a js file named main.js with the following code −
// Import events module
var events = require('events');
// Create an eventEmitter object
vareventEmitter = new
events.EventEmitter();
// Create an event handler as follows
varconnectHandler = function connected()
{ console.log('connection succesful.');
// Fire the data_received event
eventEmitter.emit('data_received');
}
// Bind the connection event with the handler
eventEmitter.on('connection',
connectHandler);
Streams
Streams are objects that let you read data from a source or write data to a destination in continuous fashion.
In Node.js, there are four types of streams −
Readable − Stream which is used for read operation.
Writing to a Stream
Create a js file named main.js with the following code −
var fs = require("fs");
var data = 'Simply Easy Learning';
// Create a writable stream
varwriterStream = fs.createWriteStream('output.txt');
// Write the data to stream with encoding to be
utf8 writerStream.write(data,'UTF8');
// Mark the end of
file
writerStream.end();
// Handle stream events --> finish, and
Dr. S. Mohamed Iliyas, Assistant Professor of Computer Science, P a g e 18
JMC, Trichy
error writerStream.on('finish', function() {
console.log("Write completed.");
});
File System
Node implements File I/O using simple wrappers around standard POSIX functions. The Node File
System (fs) module can be imported using the following syntax −
var fs = require("fs")
Synchronous vs Asynchronous
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 former
never blocks a program during its execution, whereas the second one does.
Example
Create a text file named input.txt with the following content −
This material gives self learning content to teach the world in simple and easy way!!!!!
Let us create a js file named main.js with the following code −
var fs = require("fs");
// Asynchronous read
fs.readFile('input.txt', function (err, data)
{
if (err) {
return console.error(err);
}
console.log("Asynchronous read: " + data.toString());
});
// Synchronous read
var data = fs.readFileSync('input.txt');
console.log("Synchronous read: " +
data.toString()); console.log("Program Ended");
Now run the main.js to see the result −
$ node main.js
Verify the Output.
Synchronous read: This material givesself learning contentto teach the world in simple and easy way!!!!!
Program Ended
Asynchronous read: This material givesself learning contentto teach the world in simple and
easy way!!!!!
Open a File
Syntax
Flags
Flags for read/write operations are −
Sr.No. Flag & Description
1 r - Open file for reading. An exception occurs if the file does not exist.
2 r+Open file for reading and writing. An exception occurs if the file does not exist.
4 rs+Open file for reading and writing, asking the OS to open it synchronously. See notes for
'rs' about using this with caution.
5 wOpen file for writing. The file is created (if it does not exist) or truncated (if it exists).
7 w+Open file for reading and writing. The file is created (if it does not exist) or truncated (if
it exists).
9 aOpen file for appending. The file is created if it does not exist.
11 a+Open file for reading and appending. The file is created if it does not exist.
Example
Let us create a js file named main.js having the following code to open a file input.txt for reading and
writing.
var fs = require("fs");
// Asynchronous - Opening File
console.log("Going to open file!");
fs.open('input.txt', 'r+', function(err, fd)
{
if (err) {
return console.error(err);
}
console.log("File opened successfully!");
});
Now run the main.js to see the result −
Dr. S. Mohamed Iliyas, Assistant Professor of Computer Science, P a g e 23
JMC, Trichy
$ node main.js
Verify the Output.
Going to open file!
File opened successfully!
Parameters
Here is the description of the parameters used −
path − This is the string having file name including path.
callback − This is the callback function which gets two arguments (err, stats) where stats is an
object of fs.Stats type which is printed below in the example.
Apart from the important attributes which are printed below in the example, there are several useful methods
available in fs.Stats class which can be used to check file type. These methods are given in the following
table.
Sr.No. Method & Description
Writing a File
Syntax
Following is the syntax of one of the methods to write into a file −
fs.writeFile(filename, data[, options], callback)
This method will over-write the file if the file already exists. If you want to write into an existing file then
you should use another method available.
Parameters
Here is the description of the parameters used −
path − This is the string having the file name including path.
data − This is the String or Buffer to be written into the file.
options − The third parameter is an object which will hold {encoding, mode, flag}. By default.
encoding is utf8, mode is octal value 0666. and flag is 'w'
callback − This is the callback function which gets a single parameter err that returns an error in case
of any writing error.
Reading a File
Syntax
Following is the syntax of one of the methods to read from a file −
fs.read(fd, buffer, offset, length, position, callback)
Closing a File
Syntax
Following is the syntax to close an opened file −
fs.close(fd, callback)
Parameters
Here is the description of the parameters used −
fd − This is the file descriptor returned by file fs.open() method.
callback − This is the callback function No arguments other than a possible exception are given to
the completion callback.
Truncate a File
Syntax
Following is the syntax of the method to truncate an opened file −
fs.ftruncate(fd, len, callback)
Parameters
Here is the description of the parameters used −
fd − This is the file descriptor returned by fs.open().
len − This is the length of the file after which the file will be truncated.
callback − This is the callback function No arguments other than a possible exception are given to
the completion callback.
Delete a File
Syntax
Following is the syntax of the method to delete a file −
fs.unlink(path, callback)
Parameters
Here is the description of the parameters used −
path − This is the file name including path.
callback − This is the callback function No arguments other than a possible exception are given to
the completion callback.
Create a Directory
Syntax
Following is the syntax of the method to create a directory −
fs.mkdir(path[, mode], callback)
Parameters
Here is the description of the parameters used −
path − This is the directory name including path.
mode − This is the directory permission to be set. Defaults to 0777.
callback − This is the callback function No arguments other than a possible exception are given to
the completion callback.
Remove a Directory
Syntax
Following is the syntax of the method to remove a directory −
fs.rmdir(path, callback)
Parameters
Here is the description of the parameters used −
path − This is the directory name including path.
callback − This is the callback function No arguments other than a possible exception are given to
the completion callback.
Utility Modules
There are several utility modules available in Node.js module library. These modules are very common
and are frequently used while developing any Node based application.
Sr.No. Module Name & Description
2 Path Module - Provides utilities for handling and transforming file paths.
3 Net Module - Provides both servers and clients as streams. Acts as a network wrapper.
4 DNS Module - Provides functions to do actual DNS lookup as well as to use underlying
operating system name resolution functionalities.
5 Domain Module - Provides ways to handle multiple different I/O operations as a single
group.
OS Module
Node.js os module provides a few basic operating-system related utility functions. This module can be
imported using the following syntax.
varos = require("os")
Methods
Sr.No. Method & Description
1 os.tmpdir() - Returns the operating system's default directory for temp files.
2 os.endianness() - Returns the endianness of the CPU. Possible values are "BE" or "LE".
Properties
Sr.No. Property & Description
1 os.EOL - A constant defining the appropriate End-of-line marker for the operating system.
Path Modules
Node.js path module is used for handling and transforming file paths. This module can be imported using
the following syntax.
var path = require("path")
Methods
Sr.No. Method & Description
1 path.normalize(p) - Normalize a string path, taking care of '..' and '.' parts.
2 path.join([path1][, path2][, ...]) - Join all the arguments together and normalize the
resulting path.
Properties
Sr.No. Property & Description
3 path.posix - Provide access to aforementioned path methods but always interact in a posix
compatible way.
4 path.win32 - Provide access to aforementioned path methods but always interact in a win32
compatible way.
Net Module
Node.js net module is used to create both servers and clients. This module provides an asynchronous
network wrapper and it can be imported using the following syntax.
var net = require("net")
DNS Module
Node.js dns module is used to do actual DNS lookup as well as to use underlying operating system name
resolution functionalities. This module provides an asynchronous network wrapper and can be imported
Dr. S. Mohamed Iliyas, Assistant Professor of Computer Science, P a g e 27
JMC, Trichy
using the following syntax.
vardns = require("dns")
Domain Module
Node.js domain module is used to intercept unhandled error. These unhandled error can be intercepted using
internal binding or external binding. If errors are not handled at all, then they will simply crash the Node
application.
Internal Binding − Error emitter is executing its code within the run method of a domain.
External Binding − Error emitter is added explicitly to a domain using its add method.
This module can be imported using the following syntax.
var domain = require("domain")
The domain class of domain module is used to provide functionality of routing errors and uncaught
exceptions to the active Domain object. It is a child class of EventEmitter. To handle the errors that it
catches, listen to its error event. It is created using the following syntax −
var domain =
require("domain"); var child =
domain.create();