Introduction to node.js by Ran Mizrahi @ Reversim Summit

Post on 10-May-2015

1.463 views 1 download

Tags:

description

Node.js is a platform built on Chrome V8 javascript runtime engine for building fast and scalable, non-blocking, real-time and network applications. In this session I'll introduce you to node.js and developing large code bases using it. We'll cover the following aspects: * What is node.js? * Apache vs. Nginx performance (One thread per connection vs. event loop) and what it has to do with node.js. * Why node was written in Javascript? * Main tools and frameworks (Express, socket.io, mongoose etc.) * TDD/BDD with node.js using mocha and Expect.js

Transcript of Introduction to node.js by Ran Mizrahi @ Reversim Summit

Monday, April 1, 13

Introduction to node.js

Ran Mizrahi (@ranm8)Open Source Dpt. Leader @ CodeOasis

Monday, April 1, 13

About CodeOasis

• CodeOasis specializes in cutting-edge web solutions.

• Large variety of customers (from startups to enterprises).

• Technologies we love:

• PHP - Symfony2 and Drupal• node.js (-:• HTML5• CSS3• AngularJS

• Our Microsoft department works with C#, WPF, etc.

Monday, April 1, 13

What is node.js??

• Server-side JavaScript development platform.

• Built on top of Chrome’s JavaScript runtime engine V8.

• Aims for easy development of scalable, non-blocking I/O, real time and network applications.

• Written in C/C++ and JavaScript.

• CommonJS module system.

• node.js is single-threaded and uses event-loop.

Monday, April 1, 13

What is V8??

• V8 is Google Chrome's JavaScript runtime engine.

• Implements ECMAScript specification (5th edition).

• Standalone and can be embedded to any C++ application.

• Compiles JavaScript to native machine code before executing it instead of interpreting.

• Open sourced under the new BSD license.

Monday, April 1, 13

We all love burgers!

Monday, April 1, 13

We all love burgers!

Monday, April 1, 13

Thread per Connection Burgers Restaurant

Monday, April 1, 13

Thread per Connection Burgers Restaurant

Monday, April 1, 13

Thread per Connection Burgers Restaurant

Monday, April 1, 13

Monday, April 1, 13

Something is WRONG, we must do it BETTER!!!

Monday, April 1, 13

Event-driven Burgers Restaurant

Monday, April 1, 13

Event-driven Burgers Restaurant

Monday, April 1, 13

Apache vs. NGINX Performance

Requests per second:

Monday, April 1, 13

Apache vs. NGINX Performance

Memory usage:

Monday, April 1, 13

Apache vs. NGINX Performance

So, what is the big difference between Apache and Nginx?

• Apache uses one thread per connection.• Hard to scale.• Resource expensive.

• NGINX is single-threaded and uses event-loop for handling requests.• Easy to scale. • Lower resources consumption.

Monday, April 1, 13

What is the software doing while it queries to the DB?!?

var response = db.query('select * form users');// use the result

Blocking Code

Monday, April 1, 13

What is the software doing while it queries to the DB?!?

var response = db.query('select * form users');// use the result

In most cases, nothing (/:

Blocking Code

Monday, April 1, 13

What is the software doing while it queries to the DB?!?

var response = db.query('select * form users');// use the result

In most cases, nothing (/:

Blocking Code

• Better software should handle I/O differently! It should multitask.

• Other tasks should be performed while waiting..

Monday, April 1, 13

Non-blocking code:

Non-blocking Code

db.query('select * form users', function(result){ // Use the result});

Monday, April 1, 13

Non-blocking code:

Non-blocking Code

This is how I/O should be handled in concurrency, when the DB will respond, the given function will be executed.

db.query('select * form users', function(result){ // Use the result});

Monday, April 1, 13

So, Why Isn’t Everyone Using Non-blocking I/O

puts('Enter you name:');var name = gets();puts('Hello ' + name);

This what we learn:

Monday, April 1, 13

So, Why Isn’t Everyone Using Non-blocking I/O

puts('Enter you name:');var name = gets();puts('Hello ' + name);

This what we learn:

puts('Enter you name here:');gets(function(name) { puts('Hello ' + name);});

Considered too complicated (:/

Monday, April 1, 13

Why JavaScript?!

JavaScript is designed specifically to be used with an event-loop:

• Anonymous functions, closures.

• Only one callback at a time.

• I/O through DOM event callbacks.

• Web developers already know JavaScript (Makes the learning curve much smaller).

Monday, April 1, 13

The node.js project

• Provides purely event-driven, non-blocking infrastructure to write high concurrency applications.

• Uses JavaScript for easy development of asynchronies apps.

• Open source and extendable module system.

https://github.com/popular/starred

Monday, April 1, 13

Some Examples

Monday, April 1, 13

Hello Reversim Summit!

setTimeout(function() { console.log('Reversim Summit!'); }, 2000);

console.log('Hello');

• The program outputs “Hello”, then waits two seconds and outputs “Reversim Summit!”.

•While waiting for the timeout to complete, node.js will keep adjusting other tasks.

•Node exits automatically when nothing is left to do.

Monday, April 1, 13

Streaming HTTP Server

var http = require('http');

var server = http.createServer(function(request, response) { response.writeHead(200, { 'Content-Type': 'text/plain' }); setTimeout(function() { response.end('Reversim Summit!\n'); }, 2000);

response.write('Hello\n'); });

server.listen(8000);

Monday, April 1, 13

Streaming HTTP Server

var http = require('http');

var server = http.createServer(function(request, response) { response.writeHead(200, { 'Content-Type': 'text/plain' }); setTimeout(function() { response.end('Reversim Summit!\n'); }, 2000);

response.write('Hello\n'); });

server.listen(8000);

Let’s benchmark that... and see the results..

Monday, April 1, 13

Streaming HTTP Server

var http = require('http');

var server = http.createServer(function(request, response) { response.writeHead(200, { 'Content-Type': 'text/plain' }); setTimeout(function() { response.end('Reversim Summit!\n'); }, 2000);

response.write('Hello\n'); });

server.listen(8000);

Let’s benchmark that... and see the results..

20 secs, with single thread is the result of non-blocking structure.

Monday, April 1, 13

DNS Resolver

var dns = require('dns');

console.log('resolving google.com...');

dns.resolve('google.com', function(error, addresses) { if (error) throw error; console.log('found: ' + addresses.join(', '));});

Resolves “google.com” and outputs the result.

Monday, April 1, 13

Common Frameworks and Tools

Monday, April 1, 13

NPM (Node.js package manager)

Some of npm features:

• Easy installation and publishing of node.js modules.

• Manages module dependancies.

• Easy to use.

• Works in both global and local scope.

npm is a package and dependency manager for node.js.

Monday, April 1, 13

NPM (Node.js package manager)

npm usage:

$ npm install express -g

$ npm install express

Installs package in the current local directory:

Installs package globally

Monday, April 1, 13

Express

Some of express features:

• Robust routing.

• Redirection helpers.

• View rendering and partials support.

• Built on top of connect.

Express is a minimal and flexible node.js web framework, providing robust set of features for building web applications.Taken from http://expressjs.com

Monday, April 1, 13

Express

var express = require('express');

var app = express.createServer();app.get('/', function(request, response) { // Return JSON encoded response response.json({ code: 200, message: 'OK', payload: null });});

Web Server example:

• Creates new express HTTP server with route for path “/”.

• Returns JSON formatted response.

Monday, April 1, 13

Socket.IO

Some of socket.io main features:

• Supports multiple transport mechanisms (WebSocket, Flash and AJAX long-polling fallback, etc.).

• Management of sockets rooms and namespaces.

• Disconnections detection through heartbeats.

• Reconnection support with buffering.

Socket.IO aims to make real-time apps possible in every browser and mobile device, blurring the differences between transport mechanisms.Taken from http://socket.io

Monday, April 1, 13

Socket.IO - Simple notification example

var io = require('socket.io').listen(3000);

io.on('connection', function(socket) { var notification = { body: 'Hello Reversim Summit!' }; socket.emit('notification', notification, function(response) { console.log(response); });});

Server:

Client: var socket = io.connect('http://localhost:3000');socket.on('notification', function(data, callback) { console.log(data.body); callback('Hello to you too!');});

Monday, April 1, 13

Mongoose

Some of mongoose main features:

• Allows creating DB schemas.

• Management of sockets rooms and namespaces.

• Disconnections detection through heartbeats.

• Reconnection support with buffering.

Mongoose aims to provide elegant MongoDB object modeling (ODM) for node.js.

Monday, April 1, 13

Mongoose

var mongoose = require('mongoose');mongoose.connect('localhost', 'my_db');

var CatSchema = mongoose.Schema({ name: { required: true, default: 'My cat' }});

var Cat = mongoose.model('Cat', CatSchema);

var kitty = new Cat({ name: 'Kati' });kitty.save(function(err) { if (err) throw err; console.log('Saved!')});

Mongoose cat document example:

Monday, April 1, 13

TDD/BDD using Mocha and Expect.js

Mocha is a feature-rich JavaScript test frameworks running on node and the browser, making asynchronies tests easy.

Mocha

Main features:

• Supports both TDD and BDD styles.

• Both browser and node support.

• Proper exit status for CI support.

• Really easy async tests.

• node.js debugger support.

• Highly flexible, choose and join the pieces yourself (spy library, assertion library, etc.).

Monday, April 1, 13

TDD/BDD using Mocha and Expect.js

Expect.js is a minimalistic assertion library based on should.js Expect.js

Main features:

• BDD style.

• Compatible with all test frameworks.

• Both node.js and browser compatible.

• Standalone assertion library.

Monday, April 1, 13

TDD/BDD using Mocha and Expect.js

var expect = require('expect.js');

describe('Array', function() { describe('#indexOf()', function() { it('Expect -1 when the value is not present', function() { var array = [1, 2, 3]; expect(array.indexOf(4)).to.be(-1); }); });});

“Normal” test:

Run it..$ mocha --reporter spec Array #indexOf() ✓ Expect -1 when the value is not present

1 test complete (5 ms)

Monday, April 1, 13

TDD/BDD using Mocha and Expect.js“Async” test:var expect = require('expect.js');

function asyncCall(val ,callback) { var prefix = ' - ';

setTimeout(function() { var newString = val + prefix + 'OK';

callback(newString); }, 500);}

describe('asyncCall', function() { it('Add suffix that prefixed with - to the given string', function(done) { var testVal = 'Foo';

asyncCall(testVal, function(response) { expect(response).to.contain(testVal + ' - OK'); done(); }); });});

Let’s run it...

Monday, April 1, 13

Use Case

FXP

• Real-time notifications, forum threads and posts.

• 30,000 concurrency connections!

• We started with version 0.4 )-: and moved to 0.6..

• Today, runs on one web server for serving all those concurrent connections..

Monday, April 1, 13

Questions?Thank you!

Monday, April 1, 13