Node.js Asynchronous - Callbacks - Event Loop - Single Thread - non-blocking

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 = 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 are asynchronous that is, non-blocking. It essentially means a Node.js based servernever waits for an API to return data. The server moves to the next API aftercalling it and a notification mechanism of Events of Node.js helps the serverto 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 serverswhich 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.

·        $ npm --version
·        2.7.1

·       If you are running old version of npm then its damn easy to update it to the latest version. Justuse the following command from root:

·        $ sudo npm install npm -g

 

>npm ls | grep muter

>npm ls -g

$ npm uninstall express

 

Updating a module

Update package.json andchange the version of the dependency which to be updated and run the followingcommand.

$ npm update express

Search a module

Search package nameusing npm.

$ npm search express

 

Create a module

Creation of modulerequires package.json to be generated. Let's generate package.json using npm,which will generate basic skeleton of the package.json.

$ npm init

 

Once package.json isgenerated. Use the following command to register yourself with npm repositorysite using a valid email address.

$ npm adduser
Username: mcmohd
Password:
Email: (this IS public) mcmohd@gmail.com

Now its time to publishyour module:

$ npm publish

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

 

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, declares 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 thatc allbackf unctions are called when an asynchronous function returns its result whereas 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:

//Import events module

var events =require('events');

 

//Create an eventEmitter object

var eventEmitter=new events.EventEmitter();

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

//Bind event and even handler as follows

eventEmitter.on('eventName', eventHandler);

We can fire an event programatically as follows:

//Fire an event

eventEmitter.emit('eventName');

Example

Create a js file named main.js having the following code:

// Import eventsmodule

var events =require('events');

// Create aneventEmitter object

var eventEmitter=new events.EventEmitter();

 

// Create an eventhandler as follows

var connectHandler=function connected(){

   console.log('connection succesful.');

 

   //Fire the data_received event

   eventEmitter.emit('data_received');

}

 

// Bind the connectionevent with the handler

eventEmitter.on('connection', connectHandler);

 

// Bind thedata_received event with the anonymous function

eventEmitter.on('data_received',function(){

   console.log('data received succesfully.');

});

 

// Fire the connectionevent

eventEmitter.emit('connection');

 

console.log("ProgramEnded.");

Now let's try to run the above program as check the output:

$node main.js

This will produce following result:

connectionsuccesful.

datareceived succesfully.

ProgramEnded.

 

EventEmitter

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.

 

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 emiton property is used to bind a function with the event and emit is used to fire an event.

EventEmitter Class

As we have seen inprevious section, EventEmitter class lies in events module. It is accessibly via followingsyntax:

// Import events module
var events =require('events');
// Create an eventEmitter object
var eventEmitter =new events.EventEmitter();

 

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.

Example

Create a js file namedmain.js with the following Node.js code:

var events =require('events');
var eventEmitter =new events.EventEmitter();
 
// listener #1
var listner1 =function listner1(){
   console.log('listner1 executed.');
}
 
// 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");
 
// Fire the connection event 
eventEmitter.emit('connection');
 
// Remove the binding of listner1 function
eventEmitter.removeListener('connection', listner1);
console.log("Listner1 will not listen now.");
 
// Fire the connection event 
eventEmitter.emit('connection');
 
eventListeners =require('events').EventEmitter.listenerCount(eventEmitter,'connection');
console.log(eventListeners +" Listner(s) listening to connection event");
 
console.log("Program Ended.");

Now run the main.js tosee the result:

$ node main.js

Verify the Output

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.

 

 

http://www.tutorialspoint.com/nodejs/index.htm


Philip Roberts: Help, I’m stuck in an event-loop.

https://vimeo.com/96425312

http://2014.jsconf.eu/speakers/philip-roberts-what-the-heck-is-the-event-loop-anyway.html



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值