Intro to node.js - Ran Mizrahi (28/8/14)

Post on 25-May-2015

109 views 5 download

Tags:

Transcript of Intro to node.js - Ran Mizrahi (28/8/14)

Introduction to { node.js }

Ran Mizrahi (@ranm8)Founder and CEO, CoCycles

About { Me }

• Founder and CEO of CoCycles.

• Former Open Source Dpt. Leader of CodeOasis.

• Architected and lead the development of the Wix App Market.

• Full-stack and hands-on software engineer.

• 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.!!

What is { node.js }

• 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.!!

What is { V8 }

We All Love { Burgers }

{ Thread per Connection } Burgers Restaurant

Something is { WRONG }, we must

do it { BETTER }!!!

Event-Driven { Burgers Restaurant }

Requests per second:

{ Apache } vs. { NGINX } vs Performance

Memory usage:

{ Apache } vs. { NGINX } vs Performance

{ Apache } vs. { NGINX } vs 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.

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 (/:

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

• Other tasks should be performed while waiting..!!!

{ Blocking } I/O

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 }); !console.log(logSomething);

{ 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 (:/

So Why Everyone Aren’t Using { Non-Blocking I/O }

JavaScript is designed specifically to be used with an event-loop:!• Anonymous functions, closures.!

• Executes one callback at a time.!

• Tested over years with I/O through DOM event callbacks.!

• Web developers already know JavaScript (decreases the learning curve dramatically).

But Why { JavaScript } ?

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

Some { Examples }

Hello { JavaScript Israel }

setTimeout(function() { console.log(‘JavaScript Israel!'); }, 2000); !console.log('Hello');

• The program outputs “Hello”, then waits two seconds and outputs “JavaScript Israel!”.!•While waiting for the timeout to complete, node.js will keep

performing other tasks.

•Node exits automatically when nothing is left to do.

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(‘JavaScript Israel!\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.

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.

Common { Frameworks and Tools }

npm usage:

$ npm install express -g

$ npm install express

Installs package in the current local directory:

Installs package globally

NPM { Node Package Manager }

Some of express features:

• Robust routing.!• HTTP helpers (caching, redirection, etc.)!• Focuses on high performance.!• Simplified API for working in request/response environment.

• Large community support.!!!

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

{ Express }

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

Web Server example:

• Creates new express HTTP server with route for path GET “/api/me”.!

• Returns JSON formatted response.

{ Express }

Some of socket.io main features:

• Runs on top of Engine.IO as cross-browser/device bi-directional communication layer (XHR-polling, long-polling, WebSockets, Flash, etc.).

!• Binary Support.!

• 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

{ Socket.IO (1.0) } By Automattic

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

Server:

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

{ Socket.IO } Notifications Example

Some of mongoose main features:

• Allows creating DB schemas.!• Virtuals, Getters and Setters.!

• Easy validation of DB objects.!

• Extend easily!!!!

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

{ Mongoose }

var mongoose = require('mongoose'); mongoose.connect('localhost', ‘my-db'); !var CatSchema = mongoose.Schema({ name: { type: String, 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:

{ Mongoose }

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.).

{ TDD/BDD } using Mocha and Expect.js

Chai is a BDD/TDD assertion library for node and the browser that can be easily paired with any JavaScript testing framework.

Chai

Main features:

• BDD style.!• Compatible with all test frameworks. !• Both node.js and browser compatible. !• Standalone assertion library.

• Extend easily!

{ TDD/BDD } using Mocha and Chai

var expect = require(‘chai').expect; !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)

{ TDD/BDD } using Mocha and Chai

“Async” test:var expect = require(‘chai').expect; !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...

{ TDD/BDD } using Mocha and Expect.js

{ Use Cases }

FXP.co.il

• Real-time notifications, forum threads and posts.!• 30,000 concurrency connections!!• We started with version 0.4 )-:..!

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

!My Contributions… !• Requestify - Simplified HTTP

• winston-newrelic - Winston transporter for New Relic!!

Questions?Thank you!