34
Introduction to { node.js } Ran Mizrahi (@ranm8) Founder and CEO, CoCycles

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

Embed Size (px)

Citation preview

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

Introduction to { node.js }

Ran Mizrahi (@ranm8)Founder and CEO, CoCycles

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

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.

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

• 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 }

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

• 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 }

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

We All Love { Burgers }

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

{ Thread per Connection } Burgers Restaurant

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

Something is { WRONG }, we must

do it { BETTER }!!!

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

Event-Driven { Burgers Restaurant }

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

Requests per second:

{ Apache } vs. { NGINX } vs Performance

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

Memory usage:

{ Apache } vs. { NGINX } vs Performance

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

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

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

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

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

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

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

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 }

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

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 } ?

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

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

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

Some { Examples }

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

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.

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

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.

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

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.

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

Common { Frameworks and Tools }

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

npm usage:

$ npm install express -g

$ npm install express

Installs package in the current local directory:

Installs package globally

NPM { Node Package Manager }

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

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 }

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

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 }

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

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

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

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

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

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 }

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

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 }

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

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

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

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

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

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

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

“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

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

{ 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!!

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

Questions?Thank you!