Node.js is a very powerful JavaScript based framework/platform built on Google Chrome’s JavaScript V8 Engine. It is used to delevop I/O intensive web applications like video streaming sites, single page applications and other web application. Node.js is open source, completely free, and used by thousands of developers around the world.

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 it’s latest version is v0.10.36. Defintion of Node.js as put by its official documentation is as follows:

[callout font_size=”13px” style=”vistablue”]Node.js® is a platform built on Chrome’s JavaScript runtime for easily building fast, 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..[/callout]

Node.js is an open source, cross-platform Runtime Environment for 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 eases the developement of web application using Node.js to a great extents.

1

Node.js=Runtime Environment+JavaScript Library

Features of Node.js

Following are few of the important features which are making Node.js as the first choice of software architects.

Aynchronous and Event Driven All APIs of Node.js library are aynchronous that is non-blocking. It essentially means a Node.js based server never waits for a API to return data. Server moves to next API after calling it and a notification mechanism of Events of Node.js helps server to get 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 server to respond in a non-bloking ways and makes server highly scalable as opposed to traditional servers which create limited threads to handle requests. Node.js uses a single threaded program and same program can services much larger number of requests than traditional server like Apache HTTP Server.

No Buffering – Node.js applications never buffer any data. These applications simply output the data in chunks.

Who Uses Node.js?

Following is the link on github wiki containing an exhaustive list of projects, application and companies which are using Node.js. This list include eBay, General Electric, GoDaddy, Microsoft, PayPal, Uber, Wikipins, Yahoo!, Yammer and the list continues.

Following section guides you on how to install Node.js binary distribution on various OS.

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.

OS

Archive name

Windows

node-v0.12.0-x64.msi

Linux

node-v0.12.0-linux-x86.tar.gz

Mac

node-v0.12.0-darwin-x86.tar.gz

SunOS

node-v0.12.0-sunos-x86.tar.gz

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

Based on your OS architecture, donwload and extract the archive node-v0.12.0-osname.tar.gz into /tmp, and then finally move extracted files into /usr/local/nodejs directory. For example:

1

2

3

4

5

$cd/tmp

$wget http://nodejs.org/dist/v0.12.0/node-v0.12.0-linux-x64.tar.gz

$tar xvfz node-v0.12.0-linux-x64.tar.gz

$mkdir-p/usr/local/nodejs

$mv node-v0.12.0-linux-x64/*/usr/local/nodejs

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

OS

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 Filesnodejs. The installer should set the C:Program Filesnodejsbin 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.

Step 2: Create Server

At next step we use created http instance and call http.createServer() method to create server instance and then we bind it at port 8081 using listen method associated with server instance. Pass it a function with parameters request and response. Write the sample implementation to always return “Hello World”.

Make a request to Node.js server

Open http://127.0.0.1:8081/ in any browser and see the below result.

Congratulations, you have your first HTTP server up and running which is responding all the HTTP requests at port 8081.

REPL stands for Read Eval Print Loop and it represents a computer environment like a window console or Unix/Linux shell where a command is entered and system responds with an output in interactive mode. Node.js or Node comes bundled with a REPL environment. It performs the following desired tasks.

REPL feature of Node is very useful in experimenting with Node.js codes and to debug JavaScript codes.

Online REPL Terminal

To simplify your learning, we have setup required easy to use Node.js REPL environment online, where you can practice Node.js syntax: Launch Node.js REPL Terminal

Starting REPL

REPL can be started by simply running node on shell/console without any argument as follows.

1

$node

You will see the REPL Command prompt > where you can type any Node.js command:

1

2

$node

&gt;

Simple Expression

Let’s try simple mathematics at Node.js REPL command prompt:

1

2

3

4

5

6

$node

&gt;1+3

4

&gt;1+(2*3)-4

3

&gt;

Use Variables

You can make use variables to store values and print later like any conventional script. If var keyword is not used then value is stored in the variable and printed. Whereas if var keyword is used then value is stored but not printed. You can print variables usind console.log().

1

2

3

4

5

6

7

8

9

10

$node

&gt;x=10

10

&gt;vary=10

undefined

&gt;x+y

20

&gt;console.log("Hello World")

Hello Workd

undefined

Multiline Expression

Node REPL supports multiline expression similar to JavaScript. Let’s check the following do-while loop in action:

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 express module.

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 can not be imported using require() in Node application directly. Now Let’s try installing express module using global installation.

1

$npm install express-g

This will produce similar result but module will be installed globally. Here first line tells about the module version and its location where it is getting installed.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

<b>express@4.12.2/usr/lib/node_modules/express</b>

├──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

├──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 following command to check all the modules installed globally:

1

$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/

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 following command to uninstall a Node.js module.

1

$npm uninstall express

Once npm uninstall the package, you can verify by looking at the content of /node_modules/ directory or type the following command:

1

$npm ls

Updating a module

Update package.json and change the version of the dependency which to be updated and run the following command.

1

$npm update express

Search a module

Search package name using npm.

1

$npm search express

Create a module

Creation of module requires package.json to be generated. Let’s generate package.json using npm, which will generate basic skeleton of the package.json.

1

2

3

4

5

6

7

8

9

10

11

12

$npm init

Thisutility will walk you through creatingapackage.json file.

It only covers the most common items,andtries toguess sane defaults.

See'npm help json'fordefinitive documentation on these fields

andexactly what they do.

Use'npm install &lt;pkg&gt; --save'afterwards toinstallapackageand

save it asadependency inthe package.json file.

Press^Cat any time toquit.

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.

1

2

3

4

$npm adduser

Username:mcmohd

Password:

Email:(thisISpublic)mcmohd@gmail.com

Now its time to publish your module:

1

$npm publish

If everything is fine with your module, then it will be published in the reporsitory and will be accessible to install using npm like any other other Node.js module.

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 APIs of Node are written is such a way that they supports callbacks.

For example, a function to read a file may start reading file and return the control to execution environment immidiately so that 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 parameter. So there is no blocking or wait for File I/O. This makes Node.js highly scalable, as it can process high number of request without waiting for any function to return result.

These two examples explain the concept of blocking and non-blocking calls. First example shows that program blocks until it reads the file and then only it proceeds to end the program where as in second example, program does not wait for file reading but it just proceeded to print “Program Ended” and same time program without blocking continues reading the file.

Thus, a blocking program executes very much in sequence and from programming point of view its easier to implement the logic but non-blocking programs does not execute in sequence, so in case a program needs to use any data to be processed, it should be kept with-in the same block to make it sequential execution.

Node js is a single threaded application but it support concurrency via concept of event and callbacks. As every API of Node js are asynchronous and being a single thread, it uses async function calls to maintain the concurrency. Node uses observer pattern. Node thread keeps an event loop and whenever any task get completed, it fires the corresponding event which signals the event listener function to get executed.

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, delcares functions and then simply waits for 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.

While Events seems similar to what callbacks are. The difference lies in the fact that callback functions are called when an asynchronous function returns its result where as event handling works on the observer pattern. The functions which listens to events acts 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 is used to bind events and event listeners as follows:

How Node Applications Work?

In Node Application, any async function accepts a callback as a last parameter and the callback function accepts error as a first parameter. Let’s revisit the previous example again. Create a text file named input.txt having following content

Here fs.readFile() is a async function whose purpose is to read a file. If an error occurs during read of file, then err object will contain the corresponding error else data will contain the contents of the file. readFile passes err and data to callback function after file read operation is complete, which finally prints the content.

1

2

3

Program Ended

Tutorials Point isgiving selflearning content

toteach the world insimple andeasy way!!!!!

Many objects in Node emit events for example a net.Server emits an event each time a peer connects to it, a fs.readStream emits an event when the file is opened. All objects which emit events are instances of events.EventEmitter.

EventEmitter Class

As we have seen in previous section, EventEmitter class lies in events module. It is accessibly via following syntax:

When an EventEmitter instance faces any error, it emits an ‘error’ event. When 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.N.

method & Description

1

addListener(event, listener)
Adds a listener to the end of the listeners array for the specified event. No 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.

2

on(event, listener)
Adds a listener to the end of the listeners array for the specified event. No 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.

3

once(event, listener)
Adds a one time listener for the event. This listener is invoked only the next time the event is fired, after which it is removed. Returns emitter, so calls can be chained.

4

removeListener(event, listener)
Remove a listener from the listener array for the specified event. Caution: changes 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.

5

removeAllListeners([event])
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.

6

setMaxListeners(n)
By default EventEmitters will print a warning if more than 10 listeners are added 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.

8

emit(event, [arg1], [arg2], […])
Execute each of the listeners in order with the supplied arguments. Returns true if event had listeners, false otherwise.

Class Methods

S.N.

method & Description

1

listenerCount(emitter, event)
Return the number of listeners for a given event.

Events

S.No.

Events & Description

1

newListener

event – String The event name

listener – Function The event handler function

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.

2

removeListener

event – String The event name

listener – Function The event handler function

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.

Pure JavaScript is Unicode friendly but not nice to binary data. When dealing with TCP streams or the file system, it’s necessary to handle octet streams. Node provides Buffer class which provides instances to store raw data similar to an array of integers but corresponds to a raw memory allocation outside the V8 heap.

Buffer class is a global class and can be accessed in application without importing buffer module.

Return Value

No return value. Copies data from a region of this buffer to a region in the target buffer even if the target memory region overlaps with the source. If undefined the targetStart and sourceStart parameters default to 0 while sourceEnd defaults to buffer.length.

Parameters

Here is the description of the parameters used:

start – Number, Optional, Default: 0

end – Number, Optional, Default: buffer.length

Return Value

Returns a new buffer which references the same memory as the old, but offset and cropped by the start (defaults to 0) and end (defaults to buffer.length) indexes. Negative indexes start from the end of the buffer.