Introduction to Node.js – What is Node.js? – Why Node.js?



Introduction to Node.js – What is Node.js? – Why Node.js?

0 0


nodejs-introduction

Nodejs introduction slides

On Github sydcanem / nodejs-introduction

Introduction to Node.js

Prof. Christian Maderazo, James Santos

A Very Brief History

  • created by Ryan Dahl
  • v0.0.1 released in May 2009 (current stable v0.10.13)
  • smash hit at JSConf 2009
  • technology of the year 2012

What is Node.js?

Node.js is an event-driven I/O framework.

It's a simple and stable I/O platform built on top of Google's V8 javascript engine. V8 is a very complex virtual machine written by google. V8 is a javascript engine inside chrome.

What is Node.js?

Node.js is an event-driven I/O framework.

Good at handling lots of different I/O connections at the same time.

What is Node.js?

Node.js is an event-driven server-side javascript I/O framework.

Good at handling lots of different I/O connections at the same time.

Achieves this by making all network I/O non-blocking and file I/O asynchronous

Node is not

  • A web framework
  • A programming language

Node is

  • A tool for creating I/O based programs that need to be fast and/or handle lots of connections

Examples of I/O based programs:

  • Databases (e.g. MySQL, PostgreSQL, MongoDB, Redis, CouchDB)
  • APIs (e.g. Twitter, Facebook)
  • HTTP/WebSocket connections (from users of a web app)
  • Files (image resizer, video editor, internet radio)
Node does I/O in a different way. [Next] It's asynchronous in nature.

Why Node.js?

  • Asynchronous
- Can handle a lot of concurrent I/O connections
  • Asynchronous
  • Non-blocking
- All code runs in a single thread
  • Asynchronous
  • Non-blocking
  • Javascript
- Same language on the server and browser Javascript is very flexible. You can do whatever you want with it, without limitations. That's why there's alot of Javascript frameworks out there that is almost similar and solves the same problem. For DOM manipulation jQuery, Dojo, Prototype, Mootools, Zepto. Front-end MV frameworks Backbone, Ember, Angular. One thing that stands out is Javascript is naturally asynchronous. It allows us to code high-level asynchronous and non-blocking programs. Writing asynchronous code is as easy as a callback function which anyone who has written a jQuery event already knows how to do this.

Node Basics

  • Javascript
  • Asynchronous

Javascript

Prototype-based programming

- Javascript has no classess

- Instead, function defines objects

function Person () {}
var p = new Person()							
						

Classless programming

What classes can do for us?

  • Define local scope and namespaces
  • Allow private attribute and methods
  • Encapsulate code
  • Organize applications in an object oriented way

Prototype-based programming

function Person (firstname, lastname) {
	this.firstname = firstname;
	this.lastname = lastname;
}

// Public method 'fullName'
Person.prototype.fullName = function() {
	return this.firstname + this.lastname;
}

var p = new Person('Juan', 'dela Cruz');
						

Anti-Patterns: Javascript Imports

  • Spread code around files
  • Link libraries
  • No way to maintain private local scope/states/namespace
  • Leads to: - Name collisions - Unnecessary access

Patterns: Modules

  • An elegant way of encapsulating and reusing code
  • Takes advantage of the anonymous closure features of Javascript
  • Adopted by Node.js

Anatomy of a module

var ageLimit = 50; // private

module.exports = Person

function Person (firstname, lastname, age) {
	this.firstname = firstname;
	this.lastname = lastname;
	this.age = age;
}

Person.prototype.belowAgeLimit = function () {
	return this.age < ageLimit;
}							
						

Node modules

var http = require('http'),
  fs = require('fs'),
  mongoose = require('mongoose');
						

If you've programmed in Node, this looks familiar

Modules in the Wild

var express = require('express');
var fs = require('fs');
var io = require('socket.io');
var crypto = require('crypto');

var app	= express.createServer();
var staticDir = express.static;

io = io.listen(app);

var opts = {
  port: 1948,
  baseDir : __dirname + '/../../'
};

io.sockets.on('connection', function(socket) {
	socket.on('slidechanged', function(slideData) {
		if (typeof slideData.secret == 'undefined' || slideData.secret == null || slideData.secret === '') return;
		if (createHash(slideData.secret) === slideData.socketId) {
			slideData.secret = null;
			socket.broadcast.emit(slideData.socketId, slideData);
		};
	});
});

app.configure(function() {
	[ 'css', 'js', 'plugin', 'lib' ].forEach(function(dir) {
		app.use('/' + dir, staticDir(opts.baseDir + dir));
	});
});

app.get("/", function(req, res) {
	res.writeHead(200, {'Content-Type': 'text/html'});
	fs.createReadStream(opts.baseDir + '/index.html').pipe(res);
});

app.get("/token", function(req,res) {
	var ts = new Date().getTime();
	var rand = Math.floor(Math.random()*9999999);
	var secret = ts.toString() + rand.toString();
	res.send({secret: secret, socketId: createHash(secret)});
});

						

Asynchronous

Asynchronous programming

  • Node.js is entirely asynchronous

consider this analogy...

You go down to a fast food joint and order a cheeseburger, they will immediately take your order and then make you wait around until the cheeseburger is ready. In the meantime they can take other orders and start cooking cheeseburgers for other people. Imagine if you had to wait at the register for your cheeseburger, blocking all other people in line from ordering while they cooked your burger! This is called blocking I/O because all I/O (cooking cheeseburgers) happens one at a time. Node, on the other hand, is non-blocking, which means it can cook many cheeseburgers at once.

Asynchronous programming

  • Node.js is entirely asynchronous
  • You have to think differently

What's the output?

PHP

echo 'Hello';
sleep(2);
echo ' world.';							
						

Node.js

					
setTimeout(function () {
  console.log(' world.')
}, 2000)

console.log(' Hello');							
						

Asynchronous programming

  • Node.js is entirely asynchronous
  • You have to think differently
  • Failure to understand the event loop and I/O based model could lead to anti-patterns (bad code)

Node uses an event-loop to perform non-blocking and asynchronous I/O

an event-loop is a mechanism which allows you to specify what happens when a particular event occurs. You can think of it as a simple list of tasks bound to be executed when a certain event occurs.

consider this jQuery code...

$.post('/resource.json', function (data) {
	console.log(data)
});
This jQuery program performs an HTTP request resource.json. When the response comes back, an anonymous function is called (the "callback") containing the argument data. If this code is blocking execution, since browsers are single threaded, if this requests took 400ms to return, any other events happening on that timeframe would wait until data comes back. Imagine the poor user experience.

Node.js simply extends this idea to I/O operations: when you start an operation like reading a file, you can pass control to back to Node and have your code run when the data has been read. For example:

// read the file /etc/passwd, and call console.log on the returned data
fs.readFile('/etc/passwd', function(err, data){
  console.log(data);
});

Core modules

Node has small group of modules (referred to as 'node core') presented to the public as API that you are intended to write programs with.

  • fs - file system handling
  • http, net, dgram - for working with network systems
  • os - module for getting os information
  • url, querystring, path - for parsing urls and paths
  • dns - module for asynchronously resolving DNS queries

and a lot more...

http://nodejs.org/api/
The interface for these modules are all asynchronous. Some of these modules also has synchronous api.

Installation

Windows

Download pre-compiled binaries from http://nodejs.org/download

Linux / Unix

$ git clone https://github.com/joyent/node
$ cd node
$ configure 
$ make && make install

Ready for actual coding