Node.js is an open source, cross-platform runtime environment for server-side and networking applications. Node.js is becoming more and more popular as NodeJS applications are written in JavaScript, and can be run within the Node.js runtime on any operating system.
The main features of Node JS area:
Event-driven / asynchronous programming
Instead of retuning values for the functions and determining the program-flow, you basically define functions that are called by the system when an interesting event occurs (event callbacks).
Events are executed by an event loop - it’s a continuous loop which performs event detection and event triggering.
Event-driven programming is a programming style whereby the flow is determined by the occurrence of events. Programmers register callbacks to be used as event handlers for events they are interested in, and the system invokes these handlers when those events occur. This model of programming has some advantages over the traditional blocking paradigm where, to scale, you have to use multiple processes or threads.
JavaScript is a powerful language, which is well suited for this style of programming, mainly because it has first-class functions and closures.
Defining feature of Node: Event-driven / asynchronous programming
Here, instead of using the return value, you define functions that are called by the system when interesting event occurs (event callbacks). this is accompanied by an event loop - it’s a continuous loop which performs event detection and event triggering.
“Event-driven programming is a programming style whereby the flow is determined by the occurrence of events. Programmers register callbacks to be used as event handlers for events they are interested in, and the system invokes these handlers when those events occur. This model of programming has some advantages over the traditional blocking paradigm where, to scale, you have to use multiple processes or threads.
JavaScript is a powerful language, which is well suited for this style of programming, mainly because it has first-class functions and closures.”
prints the message to the console console.log(‘Hello World!');
https://www.npmjs.org - centralized repository of public modules
NPM modes of operation: global / local
Default - local, i.e. doesn’t make system wide changes - always use the default local mode if you are in a doubt.
All packages will be installed into /usr/local/lib/node_modules, uses –g flag for Global mode.
# insalling sax module globally sudo npm install -g sax
Now in any script file, you can then use sax module by using var sax = require(‘sax’);
Default mode, downloads the modules into node_modules directory of your current working directory.
# installing sax module using local mode sudo npm install sax
# install 0.2.5 version of sax module sudo npm install sax@0.2.5
# installs the latest release of the 0.2 branch sudo npm install sax@0.2.x
sudo npm install sax@“<0.3”
=0.1.0 <0.3.1\” - more complicated requirement”}” data-sheets-userformat=”{“2”:641,“3”:{“1”:0},“10”:1,“12”:0}“># you can have more complicated requirements sudo npm install sax@“>=0.1.0 <0.3.1”
# remove a module locally sudo npm uninstall # remove a module globally sudo npm -g uninstall
# updates an installed module
npm update # update a globally installed module “}” data-sheets-userformat=”{“2”:641,“3”:{“1”:0},“10”:1,“12”:0}“>npm update -g
You can use package.json one to define the dependencies and packages which you want to install. Later, you can use the “npm install” command which will read the contents of the package.json file and install accordingly.
Example of package.json file:
{ “name” : “MyApp”, “version” : “1.0.0”, “dependencies” : { “sax” : “0.3.x”, “nano” : “*", “request” : “>0.2.0” } }
You can load module by referencing: file path / name.
# including the module in your code, which exposes it’s public API for use var module = require(‘module_name’);
# exports the instance type Circle function Circle(){ } module.exports = Circle;
# exports function printA function printA(){} module.exports.printA = printA;
# loads the core http module var http = require(‘http’)
# creates a binary buffer from the utf-8 encoded string var buf = new Buffer(‘Hello World!');
# creates a binary buffer from base 64 encoded string # accepted encodings: base64, utf8, ascii var buf = new Buffer(‘8b76fde713ce’, ‘base64’); # creating a 1024-byte buffer var buf = new Buffer(1024);
# accessing an element within the buffer array of bytes console.log(buf[10]);
# manipulating contents of the buffer (setting the byte at the position 12 to 125) buf[12] = 125
# slicing a buffer - obtaing the bytes from the position 8 to 20 of the original buffer buf.slice(8, 20)
var buf2 = new Buffer(10); buf.copy(buf2, 0, 5, 10);
buf.copy(buf2, targetStart, sourceStart, sourceEnd);
# converting the buffer into a utf-8 encoded string var string = buf.toString();
# converting the buffer into a base64 encoded string var b64Str = buf.toString(‘base64’);
Event emitters allow programmers to subscribe to events they are interested in. Asynchronous programming uses the continuation-passing style (CPS) - where style takes as an argument an explicit continuation - a function of one argument.
Example of callback after finishing reading the file:
var fs = require(‘fs’); fs.readFile('/etc/passwd’, function(err, fileContent) { if (err) { throw err; } console.log(‘file content’, fileContent.toString()); });
Response object is an event emitter here, and it can emit the data and end events:
var req = http.request(options, function(response) { response.on(“data”, function(data) { console.log(“some data from the response”, data); }); response.on(“end”, function() { console.log(“response ended”); }); }); req.end();
Use CPS when you want to regain control after the requested operation completes and use the event emitter pattern when an event can happen multiple times.
Any object that implements the event emitter pattern will implement a set of methods.
.addListener and .on — To add an event listener to an event type
.once - To attach an event listener to a given event type that will be called at most once
.removeEventListener - To remove a specific event listener of a given event
.removeAllEventListeners - To remove all event listeners of a given event type
Here we say that MyClass inherits from EventEmitter - i.e the method of MyClass will be able to emit events.
util = require(‘util’); var EventEmitter = require(‘events’).EventEmitter;
// Here is the MyClass constructor: var MyClass = function() { }
util.inherits(MyClass, EventEmitter);
MyClass.prototype.someMethod = function() { this.emit(“custom event”, “argument 1”, “argument 2”); };
var myInstance = new MyClass(); myInstance.on(‘custom event’, function(str1, str2) { console.log(‘got a custom event with the str1 %s and str2 %s!', str1, str2); });