Report
Report
BY
SOURAV DAS
BY
SOURAV DAS
We would like to thanks THE TRAINERS OF THE INTERSHALA for their encouragement to select and
to work out logics and to ease the obstacles hurdles during this training. We also express our thanks to
all the other staffs for their kind co-operation and information support during the course of the
training.
We would like to thanks MR. SERVESH AGARVAL CEO & FOUNDER OF THE INTERNSHALA
TRAINING, who has been a constant source of encouragement and inspiration throughout the training
period. We also express our thanks to all other staffs for their kind co-operation and information
support during course of the work.
We would like to thanks, MR. SHATYAJIT GHARAMI, DEPARTMENT IN-CHARGE (CSE) for
hisconstant review of progress of the internship training. Last but not the least with the core of our
heart we would like to thanks our friends for their help, co-operation and thee valuable suggestion
above all, would like to give our devotion to “almighty god” who blessed us to achieve this success.
The aim of this internship training is to learn about the NODE JS PROGRAMMING and its working
principles for communication and how the manage the network issue while the weather condition is bad, how
they resolving the connectivity. And also what is the future approach for the remote areas
NODE.JS
1. Introduction
What is Node.js?
Features of Node.js
Who Uses Node.js?
Concepts
Where to Use Node.js?
Where Not to Use Node.js?
2. Environment Setup
Try it Option Online
Local Environment Setup
Text Editor
The Node.js Runtime
Download Node.js Archive
Installation on UNIX/Linux/MacOSX and SunOS
Installation on Windows
Verify Installation: Executing a File
3. First Application
Creating Node.js Application
4. REPL Terminal
Online REPL Terminal
REPL Commands
Stopping REPL
5. NPM
Installing Modules using NPM
Global vs Local Installation
Using package.json
Attributes of Package.json
Uninstalling a Module
Updating a Module
Search a Module
Create a Module
6. Callback Concept
What is Callback?
Blocking Code Example
Non-Blocking Code Example
7. Event Loop
Event-Driven Programming
Example
How Node Applications Work?
8. Event Emitter
EventEmitter Class
Methods
Class Methods
Events
Example
9. Buffers
Creating Buffers
Writing to Buffers
Reading from Buffers
Convert Buffer to JSON
Concatenate Buffers
Compare Buffers
Copy Buffer
Slice Buffer
Buffer Length
Methods Reference
Class Methods
10. Streams
What are Streams?
Reading from a Stream
Writing to a Stream
Piping the Streams
Chaining the Streams
11. File System
Synchronous vs Asynchronous
Open a File
Get File Information
Writing a File
Reading a File
Closing a File
Truncate a File
Delete a File
Create a Directory
Read a Directory
Remove a Directory
Methods Reference
12. Global Objects
__filename
__dirname
setTimeout(cb, ms)
clearTimeout (t)
setInterval(cb, ms)
Global Objects
Console object
Process object
13. Utility Modules
OS Module
Path Module
Net Module
DNS Module
Domain Module
14. Web Module
What is a Web Server?
Web Application Architecture
Creating a Web Server using Node
Make a request to Node.js server
Creating a Web client using Node
15. Express Framework
Express Overview
Installing Express
Hello world Example
Request & Response
Request Object
Response Object
Basic Routing
Serving Static Files
GET Method
POST Method
File Upload
Cookies Management
16. RESTful API
What is REST Architecture?
HTTP methods
RESTful Web Services
Creating RESTful for a Library
List Users
Add Users
Show Detail
Delete a User
17. Scaling an Application
The exec() method
The spawn() Method
The fork() Method
18. Packaging
JXcore Installation
Packaging the Code
Launching JX File
NODE.JS
1. INRODUCTION
What is 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 as supplied by its official documentation 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 also provides a rich library of various JavaScript modules which simplifies the
development of web applications using Node.js to a great extent.
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 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.
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.
Page 1
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 is the link on github wiki containing an exhaustive list of projects, application and
companies which are using Node.js. This list includes eBay, General Electric, GoDaddy,
Microsoft, PayPal, Uber, Wikipins, Yahoo!, and Yammer to name a few.
Concepts
The following diagram depicts some important parts of Node.js which we will discuss in
detail in the subsequent chapters.
Streaming Cluster
DNS Add-ons
Node.js
Domain Buffer
Global Callbacks
Page 2
I/O bound Application
Data Streaming Application
Data Intensive Real-time Application (DIRT)
JSON APIs based Application
Single Page Application
Page 3
2. ENVIRONMENT SETUP
Try the following example using the Try it option available at the top right corner of the
below sample code box (on our website):
console.log("Hello World!");
For most of the examples given in this tutorial, you will find a Try it option, so just make use
of it and enjoy your learning.
Text Editor
You need to have a text editor to type your program. Examples of text editors include
Windows Notepad, OS Edit command, Brief, Epsilon, EMACS, and vim or vi.
The name and version of text editors can vary from one operating system to another. 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 they contain the program
source code. The source files for Node.js programs are typically named with the extension
".js".
Before you start programming, make sure you have one text editor in place and you have
enough experience in how to write a computer program, save it in a file, and finally execute
it.
Page 4
The Node.js Runtime
The source code that you would write in a source file is simply javascript. The Node.js
interpreter interprets and executes 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.
The following section explains how to install Node.js binary distribution on various 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
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
OS Output
Linux export PATH=$PATH:/usr/local/nodejs/bin
Page 5
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 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.
console.log("Hello, World!")
$ node main . js
If everything is fine with your installation, it should produce the following result:
Hello, World!
Page 6
3. FIRST APPLICATION
Before creating an actual "Hello, World!" application using Node.js, let us see the
components of a Node.js application. A Node.js application consists of the following three
important components:
2. Create server: A server which will listen to client's requests similar to Apache
HTTP Server.
3. 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.
We use the require directive to load the http module and store the returned HTTP instance
into an http variable as follows:
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".
response.end('Hello World\n');
Page 7
}).listen(8081);
The above code is enough to create an HTTP server which listens, i.e, waits for a request over
8081 port on the machine.
Lest’s put step 1 and 2 together in a file called main.js and start our HTTP server as shown
below:
$ node main . js
Page 8
Congratulations, you have your first HTTP server up and running which is responding to all
the HTTP request at port 8081.
Page 9
4. 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.
● 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
$ node
>1 + 3
Page 10
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. Where as 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
undefined
>x+y
20
> console.log("Hello World")
Hello Workd
undefined
Multiline Expression
Node REPL support 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
Page 11
x: 3
x: 4
x: 5
undefined
>
..comes automatically when you press Enter after the openin g bracket. Node automatically
checks the continuity of expressions.
Underscope Variable
You can use underscope (_) 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.
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.
.save filename - save the current Node REPL session to a file.
.load filename - load file content in current Node REPL session.
Page 12
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 )
>
Page 13
5. NPM
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:
$ node - - 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:
For example, following is the command to install a famous Node.js web framework module
called express:
Page 14
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.
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.
express@4.12.2 /usr/lib/node_modules/express
├── merge-descriptors@1.0.0
├── utils-merge@1.0.0
├── cookie-signature@1.0.6
├── methods@1.1.1
├── fresh@0.2.4
├── cookie@0.1.2
├── escape-html@1.0.1
├── range-parser@1.0.2
├── content-type@1.0.1
├── finalhandler@0.3.3
├── vary@1.0.0
├── parseurl@1.3.0
├── content-disposition@0.5.0
├── path-to-regexp@0.1.3
├── depd@1.0.0
Page 15
├── qs@2.3.3
├── on-finished@2.2.0 (ee-first@1.1.0)
├── etag@1.5.1 (crc@3.2.1)
├── debug@2.1.3 (ms@0.7.0)
├── proxy-addr@1.0.7 (forwarded@0.1.0, ipaddr.js@0.1.9)
├── send@0.12.1 (destroy@1.0.3, ms@0.7.0, mime@1.3.4)
├── serve-static@1.9.2 (send@0.12.2)
├── accepts@1.2.5 (negotiator@0.5.1, mime-types@2.0.10)
└── type-is@1.6.1 (media-typer@0.3.0, mime-types@2.0.10)
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. Let's open package.json of express package present in
node_modules/express/
{
"name": "express",
"description": "Fast, unopinionated, minimalist web framework",
"version": "4.11.2",
"author": {
"name": "TJ Holowaychuk",
"email": "tj@vision-media.ca"
},
"contributors": [
{
"name": "Aaron Heckmann",
"email": "aaron.heckmann+github@gmail.com"
},
{
"name": "Ciaran Jessup",
"email": "ciaranj@gmail.com"
Page 16
},
{
"license": "MIT",
"repository": {
"type": "git",
"url": "https://github.com/strongloop/express"
},
"homepage": "http://expressjs.com/",
"keywords": [
"express",
"framework",
"sinatra",
"web",
Page 17
"rest",
"restful",
"router",
"app",
"api"
],
"dependencies": {
"accepts": "~1.2.3",
"content-disposition": "0.5.0",
"cookie-signature": "1.0.5",
"debug": "~2.1.1",
"depd": "~1.0.0",
"escape-html": "1.0.1",
"etag": "~1.5.1",
"finalhandler": "0.3.3",
"fresh": "0.2.4",
"media-typer": "0.3.0",
"methods": "~1.1.1",
"on-finished": "~2.2.0",
"parseurl": "~1.3.0",
"path-to-regexp": "0.1.3",
"proxy-addr": "~1.0.6",
"qs": "2.3.3",
"range-parser": "~1.0.2",
"send": "0.11.1",
"serve-static": "~1.8.1",
"type-is": "~1.5.6",
"vary": "~1.0.0",
"cookie": "0.1.2",
"merge-descriptors": "0.0.2",
"utils-merge": "1.0.0"
},
"devDependencies": {
Page 18
"after": "0.8.1",
"ejs": "2.1.4",
"istanbul": "0.3.5",
"marked": "0.3.3",
"mocha": "~2.1.0",
"should": "~4.6.2",
"supertest": "~0.15.0",
"hjs": "~0.0.6",
"body-parser": "~1.11.0",
"connect-redis": "~2.2.0",
"cookie-parser": "~1.3.3",
"express-session": "~1.10.2",
"jade": "~1.9.1",
"method-override": "~2.3.1",
"morgan": "~1.5.1",
"multiparty": "~4.1.1",
"vhost": "~3.0.0"
},
"engines": {
"node": ">= 0.10.0"
},
"files": [
"LICENSE",
"History.md",
"Readme.md",
"index.js",
"lib/"
],
"scripts": {
Page 19
require test/support/env --reporter dot --check-leaks test/
test/acceptance/",
},
"gitHead": "63ab25579bda70b4927a179b580a9c580b6c7ada",
"bugs": {
"url": "https://github.com/strongloop/express/issues"
},
"_id": "express@4.11.2",
"_shasum": "8df3d5a9ac848585f00a0777601823faecd3b148",
"_from": "express@*",
"_npmVersion": "1.4.28",
"_npmUser": {
"name": "dougwilson",
"email": "doug@somethingdoug.com"
},
"maintainers": [
{
"name": "tjholowaychuk",
"email": "tj@vision-media.ca"
},
{
"name": "jongleberry",
"email": "jonathanrichardong@gmail.com"
},
{
"name": "shtylman",
Page 20
"email": "shtylman@gmail.com"
},
{
"name": "dougwilson",
"email": "doug@somethingdoug.com"
},
{
"name": "aredridel",
"email": "aredridel@nbtsc.org"
},
{
"name": "strongloop",
"email": "callback@strongloop.com"
},
{
"name": "rfeng",
"email": "enjoyjava@gmail.com"
}
],
"dist": {
"shasum": "8df3d5a9ac848585f00a0777601823faecd3b148",
"tarball": "http://registry.npmjs.org/express/-/express-4.11.2.tgz"
},
"directories": {},
"_resolved": "https://registry.npmjs.org/express/-/express-4.11.2.tgz",
"readme": "ERROR: No README data found!"
Attributes of Package.json
name - name of the package
version - version of the package
description - description of the package
Page 21
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.
Once NPM uninstalls the package, you can verify it by looking at the content of
/node_modules/ directory or type the following command:
$ npm is
Updating a Module
Update package.json and change the version of the dependency to be updated and run the
following command.
Search a Module
Search a package name using NPM.
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.
Page 22
$ npm init
This utility will walk you through creating a package.json file.
It only covers the most common items, and tries to guess sane defaults.
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.
$ npm adduser
Username: mcmohd
Password:
Email: (this IS public) mcmohd@gmail.com
$ 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.
Page 23
6. CALLBACK CONCEPT
What is Callback ?
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 a 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.
var fs = require("fs");
console.log(data.toString());
console.log("Program Ended");
$ node main.js
Page 24
to teach the world in simple and easy way!!!!!
Program Ended
var fs = require("fs");
console.log("Program Ended");
$ node main.js
Program Ended
Tutorials Point is giving 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.
Page 25
7. EVENT LOOP
Node.js is a single-threaded application, but it can support concurrency via the concept of
event and callbacks. Every API of Node.js is asynchronous and being single-threaded, they
use async function calls to maintain concurrency. Node uses observer pattern. Node thread
keeps an event loop and whenever a task gets completed, it fires the corresponding event
which signals the event-listener function to execute.
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.
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:
Page 26
var eventEmitter = new events.EventEmitter();
// Fire an event
eventEmitter.emit('eventName');
Example
Create a js file named main.js with the following code:
Page 27
// Bind the data_received event with the anonymous function
eventEmitter.on('data_received', function(){
console.log('data received successfully.');
});
console.log("Program Ended.");
Now let's try to run the above program and check its output:
$ mnode main.js
connection successful.
data received successfully.
Program Ended.
var fs = require("fs");
Page 28
}
console.log(data.toString());
});
console.log("Program Ended");
Here fs.readFile() is a async function whose purpose is to read a file. If an error occurs during
the read operation, then the err object will contain the corresponding error, else data will
contain the contents of the file. readFile passes err and data to the callback function after the
read operation is complete, which finally prints the content.
Program Ended
Tutorials Point is giving self learning content
to teach the world in simple and easy way!!!!!
Page 29
8. EVENT EMITTER
Many objects in a Node emit events, for example, a net.Server emits an event each time a
peer connects to it, an fs.readStream emits an event when the file is opened. All objects
which emit events are the instances of events.EventEmitter
EventEmitter Class
As we have seen in the previous section, EventEmitter class lies in the events module. It is
accessible via the following code:
When an EventEmitter instance faces any error, it emits an 'error' event. When a new
listener is added, 'newListener' event is fired and when a listener is removed,
'removeListener' event is fired.
EventEmitter provides multiple properties like on and emit. on property is used to bind a
function with the event and emit is used to fire an event.
Methods
S.No. Method & Description
addListener(event, listener)
Adds a listener at the end of the listeners array for the specified event. No
1 checks are made to see if the listener has already been added. Multiple calls
passing the same combination of event and listener will result in the listener
being added multiple times. Returns emitter, so calls can be chained.
on(event, listener)
Adds a listener at the end of the listeners array for the specified event. No
2 checks are made to see if the listener has already been added. Multiple calls
passing the same combination of event and listener will result in the listener
being added multiple times. Returns emitter, so calls can be chained.
once(event, listener)
Adds a one-time listener to the event. This listener is invoked only the next time
3 the event is fired, after which it is removed. Returns emitter, so calls can be
chained.
Page 30
removeListener(event, listener)
Removes a listener from the listener array for the specified event. Caution: It
4 changes the array indices in the listener array behind the listener. removeListener
will remove, at most, one instance of a listener from the listener array. If any single
listener has been added multiple times to the listener array for the specified event,
then removeListener must be called multiple times to remove each instance.
Returns emitter, so calls can be chained.
removeAllListeners([event])
5 Removes all listeners, or those of the specified event. It's not a good idea to
remove listeners that were added elsewhere in the code, especially when it's on
an emitter that you didn't create (e.g. sockets or file streams). Returns emitter,
so calls can be chained.
setMaxListeners(n)
By default, EventEmitters will print a warning if more than 10 listeners are added
6 for a particular event. This is a useful default which helps finding memory leaks.
Obviously not all Emitters should be limited to 10. This function allows that to be
increased. Set to zero for unlimited.
7 listeners(event)
Returns an array of listeners for the specified event.
Class Methods
S.No. Method & Description
1 listenerCount(emitter, event)
Returns the number of listeners for a given event.
Page 31
Events
S.No. Events & Description
newListener
This event is emitted any time a listener is added. When this event is triggered,
the listener may not yet have been added to the array of listeners for the event.
removeListener
This event is emitted any time someone removes a listener. When this event is
triggered, the listener may not yet have been removed from the array of listeners
for the event.
Example
Create a js file named main.js with the following Node.js code:
// listener #1
var listner1 = function listner1() {
console.log('listner1 executed.');
}
Page 32
// listener #2
var listner2 = function listner2() {
console.log('listner2 executed.');
}
// Bind the connection event with the listner1 function
eventEmitter.addListener('connection', listner1);
// Bind the connection event with the listner2 function
eventEmitter.on('connection', listner2);
var eventListeners =
require('events').EventEmitter.listenerCount(eventEmitter,'connection');
console.log(eventListeners + " Listner(s) listening to connection event");
eventListeners =
require('events').EventEmitter.listenerCount(eventEmitter,'connection');
console.log(eventListeners + " Listner(s) listening to connection event");
console.log("Program Ended.");
$ node main.js
Verify the Output.
Page 33
2 Listner(s) listening to connection event
listner1 executed.
listner2 executed.
Listner1 will not listen now.
listner2 executed.
1 Listner(s) listening to connection event
Program Ended.
Page 34
JAVASCRIPT
1. JAVASCRIPT-OVERVIEW
What is JavaScript?
JavaScript is a dynamic computer programming language. It is lightweight and most
commonly used as a part of web pages, whose implementations allow client-side script to
interact with the user and make dynamic pages. It is an interpreted programming language
with object-oriented capabilities.
JavaScript was first known as LiveScript, but Netscape changed its name to JavaScript,
possibly because of the excitement being generated by Java. JavaScript made its first
appearance in Netscape 2.0 in 1995 with the name LiveScript. The general-purpose core
of the language has been embedded in Netscape, Internet Explorer, and other web
browsers.
The ECMA-262 Specification defined a standard version of the core JavaScript language.
Client-Side JavaScript
Client-side JavaScript is the most common form of the language. The script should be
included in or referenced by an HTML document for the code to be interpreted by the
browser.
It means that a web page need not be a static HTML, but can include programs that interact
with the user, control the browser, and dynamically create HTML content.
The JavaScript client-side mechanism provides many advantages over traditional CGI server-
side scripts. For example, you might use JavaScript to check if the user has entered a valid e-
mail address in a form field.
The JavaScript code is executed when the user submits the form, and only if all the entries are
valid, they would be submitted to the Web Server.
JavaScript can be used to trap user-initiated events such as button clicks, link navigation, and
other actions that the user initiates explicitly or implicitly.
Advantages of JavaScript
The merits of using JavaScript are:
Less server interaction: You can validate user input before sending the page off to
the server. This saves server traffic, which means less load on your server.
Immediate feedback to the visitors: They don't have to wait for a page reload to see
if they have forgotten to enter something
Increased interactivity: You can create interfaces that react when the user hovers
over them with a mouse or activates them via the keyboard.
Richer interfaces: You can use JavaScript to include such items as drag-anddrop
components and sliders to give a Rich Interface to your site visitors .
Limitations of JavaScript
We cannot treat JavaScript as a full-fledged programming language. It lacks the following
important features:
Client-side JavaScript does not allow the reading or writing of files. This has been
kept for security reason.
JavaScript cannot be used for networking applications because there is no such
support available.
JavaScript doesn't have any multithreading or multiprocessor capabilities. Once again,
JavaScript is a lightweight, interpreted programming language that allows you to
build interactivity into otherwise static HTML pages.
is an interpreted language inside the context of a web browser, you don't even need to
buy a compiler. To make our life simpler, various vendors have come up with very nice
JavaScript editing tools. Some of them are listed here:
Microsoft FrontPage: Microsoft has developed a popular HTML editor called
FrontPage. FrontPage also provides web developers with a number of JavaScript
tools to assist in the creation of interactive websites.
Macromedia Dreamweaver MX: Macromedia Dreamweaver MX is a very popular
HTML and JavaScript editor in the professional web development crowd. It provides
several handy prebuilt JavaScript components, integrates well with databases, and
conforms to new standards such as XHTML and XML.
Macromedia HomeSite 5: HomeSite 5 is a well-liked HTML and JavaScript editor
from Macromedia that can be used to manage personal websites effectively.
The specification for JavaScript 2.0 can be found on the following site:
http://www.ecmascript.org/
Today, Netscape's JavaScript and Microsoft's JScript conform to the ECMAScript standard,
although both the languages still support the features that are not a part of the standard .
2. JAVA SCRIPT SYNTAX
JavaScript can be implemented using JavaScript statements that are placed within the
<script>...</script>HTML tags in a web page.
You can place the<script> tags, containing your JavaScript, anywhere within you web page,
but it is normally recommended that you should keep it within the<head> tags.
The <script> tag alerts the browser program to start interpreting all the text between these
tags as a script. A simple syntax of your JavaScript will appear as follows.
<script ...>
JavaScript code
</script>
Language: This attribute specifies what scripting language you are using. Typically,
its value will be javascript. Although recent versions of HTML (and XHTML, its
successor) have phased out the use of this attribute.
Type: This attribute is what is now recommended to indicate the scripting language in
use and its value should be set to "text/javascript".
JavaScript code
</script>
Your First JavaScriptCode
Let us take a sample example to print out "Hello World". We added an optional HTML
comment that surrounds our JavaScript code. This is to save our code from a browser that
does not support JavaScript. The comment ends with a "//-->". Here "//" signifies a comment
in JavaScript, so we add that to prevent a browser from readingthe end of the HTML
comment as a piece of JavaScript code. Next, we call a function document.write which
writes a string into our HTML document.
This function can be used to write text, HTML, or both. Take a look at the following code.
<html>
<body>
<!--
//-->
</script>
</body>
</html>
Hello world
<script language=”JavaScript“type="text/javascript">
<!—
Var1= 10
Var2= 20
//-->
<script>
But when formatted in a single line as follows, you must use semicolons:
<!-->
//
<s/script>
Case Sensitivity
JavaScript is a case-sensitive language. This means that the language keywords, variables,
function names, and any other identifiers must always be typed with a consistent
capitalization of letters.
So the identifiers Time and TIME will convey different meanings in JavaScript.
NOTE: Care should be taken while writing variable and function names in JavaScript .
Comments in JavaScript
JavaScript supports both C-style and C++-style comments. Thus:
Any text between the characters /* and */ is treated as a comment. This may span
multiple lines
The HTML comment closing sequence --> is not recognized by JavaScript so it
should be written as //-->.
Any text between a// and the end of a line is treated as a comment and is ignored by
JavaScript.
JavaScript also recognizes the HTML comment opening sequence <1-- , JavaScript
treats this as a single-line comment, just as it does the // comment.
Example:
The following example shows how to use comments in JavaScript
All the modern browsers come with built-in support for JavaScript. Frequently, you may need
to enable or disable this support manually. This chapter explains the procedure of enabling
and disabling JavaScript support in your browsers: Internet Explorer, Firefox, chrome, and
Opera.
Finally click OK and come out. To disable JavaScript support in your Internet Explorer,
you need to select Disable radio button under Active scripting.
JavaScript in Firefox
Here are the steps to turn on or turn off JavaScript in Firefox:
Then you will find the warning dialog.!Select I’ll be careful, I promise
Then you will find the list of configure options in the browser.
There you will find the option to enable or disable javascript by right-clicking on the value
of that option ->select toggle.
JavaScript in Chrome
Here are the steps to turn on or turn off JavaScript in Chrome:\
Click the Chrome menu at the top right hand corner of your browser.
Select Settings.
In the "Javascript" section, select "Do not allow any site to run JavaScript" or "Allow all
sites to run JavaScript (recommended)".
JavaScript in Opera
Here are the steps to turn on or turn off JavaScript in Opera:
Finally click OK and come out. To disable JavaScript support in Opera, you should not
select the Enable JavaScript checkbox.
You can add a noscript block immediately after the script block as follows :
<html>
<body>
//-->
</script
<noscript>
</noscript>
</body>
</html
Now, if the user's browser does not support JavaScript or JavaScript is not enabled, then the message
from will be displayed on the screen
4. JAVASCRIPT – PLACEMENT
In the following section, we will see how we can place JavaScript in an HTML file in
different ways.
alert("Hello World")
//-->
</script>
</head>
<body>
</body>
</html>
<html>
<head>
</head>
<body>
<script type="text/javascript">
<!--
document.write("Hello World")
//-->
</script>
</body>
</html>
Hello World
You can put your JavaScript code in <head> and <body> section altogether as follows.
<html>
<head>
<script type="text/javascript">
<!--
functionsayHello() {
alert("Hello World")
}
//-->
</script>
</head>
<body>
<script type="text/javascript">
<!—
//-->
document.write("Hello
</script>
World")
</body>
</html>
Hello world
Say hello
JavaScript in External File
As you begin to work more extensively with JavaScript, you will be likely to find that there
are cases where you are reusing identical JavaScript code on multiple pages of a site. You are
not restricted to
<html>
<head>
</head>
<body
.......
be maintaining identical code in multiple HTML files. The script tag provides a mechanism
to allow</body>
you to store JavaScript in an external file and then include it into your HTML files.
Here is an example to show how you can include an external JavaScript file in your HTML
</html>
code using script tag and its src attribute
To use JavaScript from an external file source, you need to write all your JavaScript
source code in a simple text file with the extension ".js" and then include that file as shown
above. For example, you can keep the following content in filename.js file and then you can
use sayHello function in your HTML file after including the filename.js file.
functionsayHello() {
alert("Hello World")
}
5. JAVASCRIPT-VARIABLES
JavaScript Datatypes
One of the most fundamental characteristics of a programming language is the set of data
types it supports. These are the type of values that can be represented and manipulated in a
programming language. JavaScript allows you to work with three primitive data types:
JavaScript also defines two trivial data types, null and undefined, each of which
defines only a single value. In addition to these primitive data types, JavaScript supports a
composite data type known as object. We will cover objects in detail in a separate chapter.
Note: Java does not make a distinction between integer values and floating-point values. All
numbers in JavaScript are represented as floating-point values. JavaScript represents numbers
using the 64-bit floating-point format defined by the IEEE 754 standard.
JavaScript Variable
Like many other programming languages, JavaScript has variables. Variables can be thought
of as named containers. You can place data into these containers and then refer to the data
simply by naming the container. Before you use a variable in a JavaScript program, you must
declare it. Variables are declared with the var keyword as follows.
<script type>
<!—
VAR MONEY;
VAR NAME;
//-->
</script>
You can also declare multiple variables with the same var keyword as follows:
<script type="text/javascript">
<!--
<script type="text/javascript">
<!--
var money;
money = 2000.50;
//-->
</script>
Storing a value in a variable is called variable initialization. You can do variable initialization
at the time of variable creation or at a later point in time when you need that variable.
For instance, you might create a variable named money and assign the value 2000.50 to it
later. For another variable, you can assign a value at the time of initialization as follows.
<script type="text/javascript">
<!--
var money;
money = 2000.50;
//-->
</script>
Note: Use the var keyword only for declaration or initialization, once for the life of any
variable name in a document. You should not re-declare same variable twice. JavaScript is
untyped language. This means that a JavaScript variable can hold a value of any data type.
Unlike many other languages, you don't have to tell JavaScript during variable declaration
what type of value the variable will hold. The value type of a variable can change during the
execution of a program and JavaScript takes care of it automatically
JavaScript Variable Scope
The scope of a variable is the region of your program in which it is defined. JavaScript
variables have only two scopes.
GlobalVariables: A global variable has global scope which means it can be defined
anywhere in your JavaScript code.
Local Variables: A local variable will be visible only within a function
Within the body of a function, a local variable takes precedence over a global variable with
the same name. If you declare a local variable or function parameter with the same name as a
global varia
<script type="text/javascript">
<!--
functioncheckscope( ) {
document.write(myVar);
//-->
</script>
local
You should not use any of the JavaScript reserved keywords as a variable name.
These keywords are mentioned in the next section. For example, break or boolean
variable names are not valid.
JavaScript variable names should not start with a numeral (0-9). They must begin with
a letter or an underscore character. For example, 123test is an invalid variable name
but _123test is a valid one.
JavaScript variable names are case-sensitive. For example, Name and name are two
different variables.
What is an Operator
Let us take a simple expression 4 + 5 is equal to 9. Here 4 and 5 are called operands and ‘+’
is called the operator. JavaScript supports the following types of operators.
Arithmetic Operators
Comparison Operators
Logical (or Relational) Operators
Assignment Operators
Conditional (or ternary) Operators
Let’s have a look at all the operators one by one
Arithmetic Operators
JavaScript supports the following arithmetic operators: Assume variable A holds 10 and
variable B holds 20, then.
1 +(Addition)
Adds to operator
2 - (Subtraction)
3 * (Multiplication)
4 / (Division)
6 ++ (Increment)
7 -- (Decrement)
Note: Addition operator (+) works for Numeric as well as Strings. e.g. "a" + 10 will give
"a10".
Example:
<html>
<body>
<!—
var b = 10;
var c =”test”
varlinebreak = “<br/>”;
result = a+b;
document .write(result);
document.write(linebreak);
document.write("a - b = ");
result = a - b;
document.write(result);
document.write(linebreak);
a = a++;
document.write("a++ = ");
result = a++;
document.write(result);
document.write(linebreak);
b = b--;
document.write("b-- = ");
result = b--;
document.write(result);
document.write(linebreak);
Output
//-->
</script>
</body>
</html>
output
a + b = 43
a - b = 23
a / b = 3.3
a%b=3
a + b + c = 43Test
a++ = 33
b-- = 10
01 == (Equal)
Checks if the value of two operands are equal or not, if yes, then the condition
becomes true.
Checks if the value of the left operand is greater than the value of the right operand, if
yes, then the condition becomes true.
03 != (Not Equal)
Checks if the value of two operands are equal or not, if the values are not equal, then
the condition becomes true.
Ex: (A != B) is true.
Checks if the value of the left operand is less than the value of the right operand, if
yes, then the condition becomes true.
Checks if the value of the left operand is greater than or equal to the value of the right
operand, if yes, then the condition becomes true.
Checks if the value of the left operand is less than or equal to the value of the right
operand, if yes, then the condition becomes true.
Example The following code shows how to use comparison operators in JavaScript.
<html>
<body>
<script type="text/javascript">
<!--
var a = 10;
var b = 20;
result = (a == b);
document.write(result);
document.write(linebreak);
document.write(result);
document.write(linebreak);
document.write(result);
document.write(linebreak);
document.write(result);
document.write(linebreak);
result = (a != b);
document.write(result);
document.write(linebreak);
Output
document.write(result);
document.write(linebreak);
//-->
</script>
<p>Set the variables to different values and different operators and then
try...</p>
</body>
(a < b) =>true
(a > b) =>false
(a != b) =>true
(a >= b) =>false
(a <= b) =>true
Set the variables to different values and different operators and then
Logical Operators
try...
JavaScript supports the following logical operators:
Assume variable A holds 10 and variable B holds 20, then:
01 If both the operands are non-zero, then the condition becomes true.
02 || (Logical OR)
If any of the two operands are non-zero, then the condition becomes true.
Ex: (A || B) is true.
03 ! (Logical NOT)
Reverses the logical state of its operand. If a condition is true, then the
Try the following code to learn how to implement Logical Operators in JavaScript .
<html>
<body>
<script type="text/javascript">
<!--
var a = true;
var b = false;
document.write(result);
document.write(linebreak);
result = (a || b);
document.write(result);
document.write(linebreak);
document.write(result);
document.write(linebreak);
//-->
</script>
<p>Set the variables to different values and different operators and then
try...</p>
</body>
</html>
Output
(a&& b) =>false
(a || b) =>true
Set the variables to different values and different operators and then
try...
BitwiseOperators
JavaScript supports the following bitwise operators:
Ex: (A & B) is 2.
02 | (BitWise OR)
Ex: (A | B) is 3.
03 ^ (Bitwise XOR)
Ex: (A ^ B) is 1.
04 ~ (Bitwise Not)
It is a unary operator and operates by reversing all the bits in the operand.
It moves all the bits in its first operand to the left by the number of places
specified in the second operand. New bits are filled with zeros. Shifting a
Ex: (A << 1) is 4.
Binary Right Shift Operator. The left operand’s value is moved right by the
Ex: (A >> 1) is 1.
This operator is just like the >> operator, except that the bits shifted in on the left are
always zero.
Ex: (A >>> 1) is 1.
Example Try the following code to implement Bitwise operator in JavaScript.
<html>
<body>
<script type="text/javascript"><!--
document.write(result);
document.write(linebreak);
result = (a | b);
document.write(result);
document.write(linebreak);
result = (a ^ b);
document.write(result);
document.write(linebreak);
document.write(result);
document.write(linebreak);
document.write(result);
document.write(linebreak);
document.write(result);
document.write(linebreak);
//-->
</script>
<p>Set the variables to different values and different operators and then
try...</p>
</body>
</html>
Output
(a & b) => 2
(a | b) => 3
(a ^ b) => 1
(~b) => -4
(a << b) => 16
(a >> b) => 0
Set the variables to different values and different operators and then
try...
AssignmentOperators
JavaScript supports the following assignment operators:
01 = (Simple Assignment )
Assigns values from the right side operand to the left side operand
It adds the right operand to the left operand and assigns the result to the
left operand.
Ex: C += A is equivalent to C = C + A
It subtracts the right operand from the left operand and assigns the result to the left
operand.
Ex: C -= A is equivalent to C = C - A
It multiplies the right operand with the left operand and assigns the result to the left
operand.
Ex: C *= A is equivalent to C = C *a
It takes modulus using two operands and assigns the result to the left operand.
Ex: C %= A is equivalent to C = C % A
It divides the left operand with the right operand and assigns the result to the left
operand.
Ex: C /= A is equivalent to C = C / A
Note: Same logic applies to Bitwise operators, so they will become <<=, >>=, >>=, &=, |=
and ^=.
<body>
<script type="text/javascript">
<!--
var a = 33;
var b = 10;
result = (a = b);
document.write(result);
document.write(linebreak);
result = (a += b);
document.write(result);
document.write(linebreak);
result = (a -= b);
document.write(result);
document.write(linebreak);
result = (a *= b);
document.write(result);
document.write(linebreak)
result = (a /= b);
document.write(result);
document.write(linebreak);
result = (a %= b);
document.write(result);
document.write(linebreak);
//-->
</script>
<p>Set the variables to different values and different operators and then
try...</p>
</body>
</html>
Output
Value of a => (a = b) => 10
Set the variables to different values and different operators and then
try...
Miscellaneous Operators
We will discuss two operators here that are quite useful in JavaScript: the conditional operator (? :)
and the typeofoperator.
Conditional Operator (? :)
The conditional operator first evaluates an expression for a true or false value and then executes one
of the two given statements depending upon the result of the evaluation.
Example
Try the following code to understand how the Conditional Operator works in
JavaScript
<html>
<body>
<script type="text/javascript">
<!--
var a = 10;
var b = 20;
Example Try the following code to understand how the Conditional Operator works in JavaScript
Example
Try the following code to understand how the Conditional Operator works in JavaScript
document.write(result);
document.write(linebreak);
document.write(result);
document.write(linebreak);
//-->
</script>
<p>Set the variables to different values and different operators and then
try...</p>
</body>s
</html>
Output
Set the variables to different values and different operators and then
try...
Typeof Operator
The typeof operator is a unary operator tha t is placed before its single operand, which
can be of any type. Its value is a string indicating the data type of the operand.
Number “number”
String “string”
Boolean “boolean”
Object “boject”
Function “Function”
undefined “undefined”
null ” null”
Example
<html>
<body>
<script type="text/javascript">
<!--
var a = 10;
var b = "String";
document.write(result);
document.write(linebreak);
document.write(result);
document.write(linebreak);
//-->
</script>
<p>Set the variables to different values and different operators and then
try...</p>
</body>
</html>
Output
Result => B is String
Set the variables to different values and different operators and then
try...