0% found this document useful (0 votes)
4 views

NodeJS UNIT-II

The document outlines a course on Distributed Technology, covering topics such as Distributed Component Architecture, Node.js, Java Servlets, Java Mail API, and Enterprise Java Beans. It includes detailed explanations of Node.js features, environment setup, and application creation, along with REPL and NPM functionalities. The document also lists textbooks and web references for further reading.
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

NodeJS UNIT-II

The document outlines a course on Distributed Technology, covering topics such as Distributed Component Architecture, Node.js, Java Servlets, Java Mail API, and Enterprise Java Beans. It includes detailed explanations of Node.js features, environment setup, and application creation, along with REPL and NPM functionalities. The document also lists textbooks and web references for further reading.
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 28

DISTRIBUTED TECHNOLOGY – 23MCA4CC18

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".

Dr. S. Mohamed Iliyas, Assistant Professor of Computer Science, Page 3


JMC, Trichy
Before starting your programming, make sure you have one text editor in place and you have enough
experience to write a computer program, save it in a file, and finally execute it.
The Node.js Runtime
The source code written in source file is simply javascript. The Node.js interpreter will be used
to interpret and execute your javascript code.
Node.js distribution comes as a binary installable for SunOS , Linux, Mac OS X, and Windows
operating systems with the 32-bit (386) and 64-bit (amd64) x86 processor architectures.
Following section guides you on how to install Node.js binary distribution on various Operating
System.

Download Node.js archive


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.
Operating System 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

Installation on UNIX/Linux/Mac OS X, and SunOS


Based on your OS architecture, download and extract the archive node-v6.3.1-osname.tar.gz into
/tmp, and then finally move extracted files into /usr/local/nodejs directory. For example:
$ cd /tmp
$ wget http://nodejs.org/dist/v6.3.1/node-v6.3.1-linux-x64.tar.gz
$ tar xvfz node-v6.3.1-linux-x64.tar.gz
$ mkdir -p /usr/local/nodejs
$ mv node-v6.3.1-linux-x64/* /usr/local/nodejs

Add /usr/local/nodejs/bin to the PATH environment variable.

Operating System Output

Linux export PATH=$PATH:/usr/local/nodejs/bin

Mac export PATH=$PATH:/usr/local/nodejs/bin

FreeBSD export PATH=$PATH:/usr/local/nodejs/bin

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.

Verify installation: Executing a File


Create a js file named main.js on your machine (Windows or Linux) having the following code.
/* Hello, World! program in node.js
*/ console.log("Hello, World!")

Dr. S. Mohamed Iliyas, Assistant Professor of Computer Science, Page 4


JMC, Trichy
Now execute main.js file using Node.js interpreter to see the result −
$ node main.js
If everything is fine with your installation, this should produce the following result −
Hello, World!

A Node.js application consists of the following three important components −


 Import required modules − We use the require directive to load Node.js modules.
 Create server − A server which will listen to client's requests similar to Apache HTTP Server.
 Read request and return response − The server created in an earlier step will read the
HTTP request made by the client which can be a browser or a console and return the
response.

Creating Node.js Application

Step 1 - Import Required Module


We use the require directive to load the http module and store the returned HTTP instance into an http
variable as follows −
var http = require("http");

Step 2 - Create Server


We use the created http instance and call http.createServer() method to create a server instance and then we
bind it at port 8081 using the listen method associated with the server instance. Pass it a function with
parameters request and response. Write the sample implementation to always return "Hello World".
http.createServer(function (request, response) {
// Send the HTTP header
// HTTP Status: 200 : OK
// Content Type: text/plain
response.writeHead(200, {'Content-Type': 'text/plain'});

// Send the response body as "Hello


World" response.end('Hello World\n');
}).listen(8081);
// Console will print the message
console.log('Server running at http://127.0.0.1:8081/');
The above code is enough to create an HTTP server which listens, i.e., waits for a request over 8081 port
on the local machine.

Step 3 - Testing Request & Response


Let's put step 1 and 2 together in a file called main.js and start our HTTP server as shown below −
var http = require("http");
http.createServer(function (request, response) {
// Send the HTTP header
// HTTP Status: 200 : OK
// Content Type: text/plain
response.writeHead(200, {'Content-Type': 'text/plain'});
// Send the response body as "Hello
World" response.end('Hello World\n');
}).listen(8081);
// Console will print the message
console.log('Server running at http://127.0.0.1:8081/');
Now execute the main.js to start the server as follows −
$ node main.js
Verify the Output. Server has started.

Dr. S. Mohamed Iliyas, Assistant Professor of Computer Science, Page 5


JMC, Trichy
Server running at http://127.0.0.1:8081/

Dr. S. Mohamed Iliyas, Assistant Professor of Computer Science, Page 6


JMC, Trichy
Open http://127.0.0.1:8081/ in any browser and observe the following result.

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

Dr. S. Mohamed Iliyas, Assistant Professor of Computer Science, Page 7


JMC, Trichy
undefined
>x+
y 20
>console.log("Hello World")
Hello
World
undefined

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.

Dr. S. Mohamed Iliyas, Assistant Professor of Computer Science, Page 8


JMC, Trichy
 Up/Down Keys − see command history and modify previous commands.
 tab Keys − list of current commands.
 .help − list of all commands.
 .break − exit from multiline expression.
 .clear − exit from multiline expression.

Dr. S. Mohamed Iliyas, Assistant Professor of Computer Science, Page 9


JMC, Trichy
 .save filename − save the current Node REPL session to a file.
 .load filename − load file content in current Node REPL session.

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)
>

NPM (Node Package Manager)


Node Package Manager (NPM) provides two main functionalities −
 Online repositories for node.js packages/modules which are searchable on search.nodejs.org
 Command line utility to install Node.js packages, do version management and
dependency management of Node.js packages.
NPM comes bundled with Node.js installables after v0.6.3 version. To verify the same, open console and
type the following command and see the result −
$ npm --
version 2.7.1
If you are running an old version of NPM then it is quite easy to update it to the latest version. Just use the
following command from root −
$ sudonpm install npm -g
/usr/bin/npm -> /usr/lib/node_modules/npm/bin/npm-
cli.js [email protected] /usr/lib/node_modules/npm

Installing Modules using NPM


There is a simple syntax to install any Node.js module −
$ npm install <Module Name>
For example, following is the command to install a famous Node.js web framework module called express −
$ npm install express
Now you can use this module in your js file as following −
var express = require('express');

Global vs Local Installation


By default, NPM installs any dependency in the local mode. Here local mode refers to the package
installation in node_modules directory lying in the folder where Node application is present. Locally
deployed packages are accessible via require() method. For example, when we installed express module, it
created node_modules directory in the current directory where it installed the express module.
$ ls -l
total
0
drwxr-xr-x 3 root root 20 Mar 17 02:23 node_modules
Alternatively, you can use npm ls command to list down all the locally installed modules.
Globally installed packages/dependencies are stored in system directory. Such dependencies can be used
in CLI (Command Line Interface) function of any node.js but cannot be imported using require() in Node
application directly. Now let's try installing the express module using global installation.
$ npm install express -g
This will produce a similar result but the module will be installed globally. Here, the first line shows the
module version and the location where it is getting installed.
[email protected] /usr/lib/node_modules/express
├── [email protected]
├── [email protected]

Dr. S. Mohamed Iliyas, Assistant Professor of Computer Science, P a g e 10


JMC, Trichy
├── [email protected]

Dr. S. Mohamed Iliyas, Assistant Professor of Computer Science, P a g e 11


JMC, Trichy
├── [email protected]
├── [email protected]
├── [email protected]
├── [email protected]
├── [email protected]
├── [email protected]
├── [email protected]
├── [email protected]
├── [email protected]
├── [email protected]
├── [email protected]
├── [email protected]
├── [email protected]
├── [email protected] ([email protected])
├── [email protected] ([email protected])
├── [email protected] ([email protected])
├── [email protected] ([email protected], [email protected])
├── [email protected] ([email protected], [email protected], [email protected])
├── [email protected] ([email protected])
├── [email protected] ([email protected], [email protected])
└── [email protected] ([email protected], [email protected])
You can use the following command to check all the modules installed globally −
$ npm ls -g

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

Dr. S. Mohamed Iliyas, Assistant Professor of Computer Science, P a g e 12


JMC, Trichy
Search a Module
Search a package name using NPM.
$ npm search 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.

See 'npm help json' for definitive documentation on these


fields and exactly what they do.

Use 'npm install <pkg> --save' afterwards to install a package


and save it as a dependency in the package.json file.

Press ^C at any time to


quit. name: (webmaster)
You will need to provide all the required information about your module. You can take help from the above-
mentioned package.json file to understand the meanings of various information demanded. Once
package.json is generated, use the following command to register yourself with NPM repository site using a
valid email address.
$ npmadduser
Username:
mcmohd Password:
Email: (this IS public) [email protected]
It is time now to publish your module −
$ npm publish
If everything is fine with your module, then it will be published in the repository and will be accessible to
install using NPM like any other Node.js module.

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.

Blocking Code 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!!!!!

Create a js file named main.js with the following code −

var fs = require("fs");
var data =
fs.readFileSync('input.txt');
console.log(data.toString());

Dr. S. Mohamed Iliyas, Assistant Professor of Computer Science, P a g e 13


JMC, Trichy
console.log("Program Ended");

Dr. S. Mohamed Iliyas, Assistant Professor of Computer Science, P a g e 14


JMC, Trichy
Now run the main.js to see the result −
$ node main.js

Verify the Output.


This material gives self-learning content to teach the world in simple and easy
way!!!!! Program Ended

Non-Blocking Code 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!!!!!
Update main.js to have the following code −
var fs = require("fs");
fs.readFile('input.txt', function (err, data)
{
if (err) return
console.error(err);
console.log(data.toString());
});
console.log("Program Ended");

Now run the main.js to see the result −


$ node main.js
Verify the Output.
Program Ended
This material gives self learning content to teach the world in simple and easy way!!!!!

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.

Dr. S. Mohamed Iliyas, Assistant Professor of Computer Science, P a g e 15


JMC, Trichy
Although events look quite similar to callbacks, the difference lies in the fact that callback functions
are called when an asynchronous function returns its result, whereas event handling works on the observer
pattern. The functions that listen to events act as Observers. Whenever an event gets fired, its listener
function starts executing. Node.js has multiple in-built events available through events module and
EventEmitter class which are used to bind events and event-listeners as follows −

// Import events module


var events = require('events');

// Create an eventEmitter object


vareventEmitter = new
events.EventEmitter();

Following is the syntax to bind an event handler with an event −


// Bind event and event handler as follows
eventEmitter.on('eventName',
eventHandler);

We can fire an event programmatically as follows −


// Fire an event
eventEmitter.emit('eventName');

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);

// Bind the data_received event with the anonymous


function eventEmitter.on('data_received', function() {
console.log('data received succesfully.');
});
// Fire the connection event
eventEmitter.emit('connection');
console.log("Program
Ended.");
Now let's try to run the above program and check its output −
$ node main.js
It should produce the following result −
connection successful.
data received
successfully. Program

Dr. S. Mohamed Iliyas, Assistant Professor of Computer Science, P a g e 16


JMC, Trichy
Ended.

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.

Dr. S. Mohamed Iliyas, Assistant Professor of Computer Science, P a g e 17


JMC, Trichy
 Writable − Stream which is used for write operation.
 Duplex − Stream which can be used for both read and write operation.
 Transform − A type of duplex stream where the output is computed based on input.
Each type of Stream is an EventEmitter instance and throws several events at different instance of times.
For example, some of the commonly used events are −
 data − This event is fired when there is data is available to read.
 end − This event is fired when there is no more data to read.
 error − This event is fired when there is any error receiving or writing data.
 finish − This event is fired when all the data has been flushed to underlying system.

Reading from a Stream


Create a text file named input.txt having the following content −
This material gives self learning content to teach the world in simple and easy way!!!!!
Create a js file named main.js with the following code −
var fs =
require("fs"); var
data = '';
// Create a readable stream
varreaderStream = fs.createReadStream('input.txt');
// Set the encoding to be utf8.
readerStream.setEncoding('UTF8')
;
// Handle stream events --> data, end, and
error readerStream.on('data', function(chunk)
{
data += chunk;
});
readerStream.on('end',function()
{ console.log(data);
});
readerStream.on('error', function(err)
{ console.log(err.stack);
});
console.log("Program Ended");

Now run the main.js to see the result −


$ node main.js

Verify the Output.


Program Ended
This material gives self learning content to teach the world in simple and easy way!!!!!

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.");
});

Dr. S. Mohamed Iliyas, Assistant Professor of Computer Science, P a g e 19


JMC, Trichy
writerStream.on('error', function(err)
{ console.log(err.stack);
});
console.log("Program Ended");

Now run the main.js to see the result −


$ node main.js
Verify the Output.
Program Ended
Write completed.
Now open output.txt created in your current directory; it should contain the following −
Simply Easy Learning

Piping the Streams


Piping is a mechanism where we provide the output of one stream as the input to another stream. It is
normally used to get data from one stream and to pass the output of that stream to another stream. There is
no limit on piping operations. Now we'll show a piping example for reading from one file and writing it to
another file.
Create a js file named main.js with the following code −
var fs = require("fs");
// Create a readable stream
varreaderStream = fs.createReadStream('input.txt');
// Create a writable stream
varwriterStream = fs.createWriteStream('output.txt');
// Pipe the read and write operationsread input.txt and write data to
output.txt readerStream.pipe(writerStream);
console.log("Program Ended");

Now run the main.js to see the result −


$ node main.js

Verify the Output.


Program Ended
Open output.txt created in your current directory; it should contain the following −
This material gives self learning content to teach the world in simple and easy way!!!!!

Chaining the Streams


Chaining is a mechanism to connect the output of one stream to another stream and create a chain of
multiple stream operations. It is normally used with piping operations. Now we'll use piping and chaining to
first compress a file and then decompress the same.
Create a js file named main.js with the following code −
var fs = require("fs");
varzlib = require('zlib');
// Compress the file input.txt to
input.txt.gz
fs.createReadStream('input.txt')
.pipe(zlib.createGzip())
.pipe(fs.createWriteStream('input.txt.gz'))
; console.log("File Compressed.");
Now run the main.js to see the result −
$ node main.js
Verify the Output.
File Compressed.

Dr. S. Mohamed Iliyas, Assistant Professor of Computer Science, P a g e 20


JMC, Trichy
You will find that input.txt has been compressed and it created a file input.txt.gz in the current directory.
Now let's try to decompress the same file using the following code −
var fs = require("fs");
varzlib = require('zlib');
// Decompress the file input.txt.gz to
input.txt fs.createReadStream('input.txt.gz')
.pipe(zlib.createGunzip())
.pipe(fs.createWriteStream('input.txt'))
; console.log("File Decompressed.");
Now run the main.js to see the result −
$ node main.js
Verify the Output.
File
Decompressed.

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

Dr. S. Mohamed Iliyas, Assistant Professor of Computer Science, P a g e 21


JMC, Trichy
Following is the syntax of the method to open a file in asynchronous mode −
fs.open(path, flags[, mode], callback)

Dr. S. Mohamed Iliyas, Assistant Professor of Computer Science, P a g e 22


JMC, Trichy
Parameters
Here is the description of the parameters used −
 path − This is the string having file name including path.
 flags − Flags indicate the behavior of the file to be opened. All possible values have been mentioned
below.
 mode − It sets the file mode (permission and sticky bits), but only if the file was created. It defaults
to 0666, readable and writeable.
 callback − This is the callback function which gets two arguments (err, fd).

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.

3 rsOpen file for reading in synchronous mode.

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).

6 wxLike 'w' but fails if the path exists.

7 w+Open file for reading and writing. The file is created (if it does not exist) or truncated (if
it exists).

8 wx+Like 'w+' but fails if path exists.

9 aOpen file for appending. The file is created if it does not exist.

10 AxLike 'a' but fails if the path exists.

11 a+Open file for reading and appending. The file is created if it does not exist.

12 ax+Like 'a+' but fails if the the path exists.

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!

Get File Information


Syntax
Following is the syntax of the method to get the information about a file −
fs.stat(path, callback)

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

1 stats.isFile()Returns true if file type of a simple file.

2 stats.isDirectory()Returns true if file type of a directory.

3 stats.isBlockDevice()Returns true if file type of a block device.

4 stats.isCharacterDevice()Returns true if file type of a character device.

5 stats.isSymbolicLink()Returns true if file type of a symbolic link.

6 stats.isFIFO()Returns true if file type of a FIFO.

7 stats.isSocket()Returns true if file type of asocket.

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)

Dr. S. Mohamed Iliyas, Assistant Professor of Computer Science, P a g e 24


JMC, Trichy
This method will use file descriptor to read the file. If you want to read the file directly using the file name,
then you should use another method available.
Parameters
Here is the description of the parameters used −
 fd − This is the file descriptor returned by fs.open().
 buffer − This is the buffer that the data will be written to.
 offset − This is the offset in the buffer to start writing at.
 length − This is an integer specifying the number of bytes to read.
 position − This is an integer specifying where to begin reading from in the file. If position is null,
data will be read from the current file position.
 callback − This is the callback function which gets the three arguments, (err, bytesRead, buffer).

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.

Dr. S. Mohamed Iliyas, Assistant Professor of Computer Science, P a g e 25


JMC, Trichy
Read a Directory
Syntax
Following is the syntax of the method to read a directory −
fs.readdir(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 which gets two arguments (err, files) where files is an
array of the names of the files in the directory excluding '.' and '..'.

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

1 OS Module - Provides basic operating-system related utility functions.

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".

3 os.hostname() - Returns the hostname of the operating system.

Dr. S. Mohamed Iliyas, Assistant Professor of Computer Science, P a g e 26


JMC, Trichy
4 os.type() - Returns the operating system name.

5 os.platform() - Returns the operating system platform.

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.

3 path.resolve([from ...], to) - Resolves to an absolute path.

4 path.isAbsolute(path) - Determines whether the path is an absolute path. An absolute path


will always resolve to the same location, regardless of the working directory.

5 path.relative(from, to) - Solve the relative path from from to to.

Properties
Sr.No. Property & Description

1 path.sep - The platform-specific file separator. '\\' or '/'.

2 path.delimiter - The platform-specific path delimiter, ; or ':'.

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();

Dr. S. Mohamed Iliyas, Assistant Professor of Computer Science, P a g e 28


JMC, Trichy

You might also like