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 emit. on 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) |
2 | on(event, listener) |
3 | once(event, listener) |
4 | removeListener(event, listener) |
5 | removeAllListeners([event]) |
6 | setMaxListeners(n) |
7 | listeners(event) |
8 | emit(event, [arg1], [arg2], [...]) |
Class Methods
S.N. | method & Description |
1 | listenerCount(emitter, 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