scalable network applications, event-driven - node js

16
JavaScript with nodeJs

Upload: cosmin-mereuta

Post on 10-May-2015

389 views

Category:

Technology


3 download

TRANSCRIPT

Page 1: Scalable network applications, event-driven - Node JS

JavaScript with nodeJs

Page 2: Scalable network applications, event-driven - Node JS

What is Node JS?A JavaScript runtime environment running Google

Chrome’s V8 engineNode.js is a platform for building fast, scalable network

applications (web servers).Server - side JavaScriptUses event-driven, asynchronous I/O to minimize overhead

and maximize scalability Great for data-intensive, real-time applications�

Page 3: Scalable network applications, event-driven - Node JS

V8 JavaScript Engine

V8 is written in C++ and is used in Google ChromeRuns on Windows (XP or newer), Mac OS X (10.5 or newer), and

Linux systems that use IA-32, x64, or ARM – you can install your server on many devices.

Page 4: Scalable network applications, event-driven - Node JS

What can NodeJS be used for?Network servers (HTTP, messaging)API backendsReal time applicationsStreaming dataWeb sitesBots

Page 5: Scalable network applications, event-driven - Node JS

Typical architecture

Page 6: Scalable network applications, event-driven - Node JS

Node Package Manager (NPM)NPM is a package management and

distribution system for Nodeyou can quickly find packages to serve

specific purposesAn npm package is a directory structure with

a package.json file describing the packageTotal Packages: over 31 000can be installed simply by typing the

following: npm install moduleName

Page 7: Scalable network applications, event-driven - Node JS

Node Package Manager (NPM)Databases: mysql, postgresql, mongodbDOM: jsdomWeb frameworks: express, connectDOM Manipulation: jQuery Utility libraries: underscore ,backbone,

request Templating: mustache, jade Testing: vows, expresso

Page 8: Scalable network applications, event-driven - Node JS

Non-blocking I/OServers do nothing but I/O (Scripts waiting on

I/O requests degrades performance )To avoid blocking, Node makes use of the event

driven nature of JS by attaching callbacks to I/O requests

fs.read('very-big-file', function(data) { complexOperation(data); }

);

// you can do a lot when waiting for data doOtherStuff();

THE NODE WAY

Page 9: Scalable network applications, event-driven - Node JS

Blocking vs Non-Blocking flow

Page 10: Scalable network applications, event-driven - Node JS

Basic HTTP ServerCODE: http = require("http");

http.createServer(function (req, res) {res.writeHead(200, {'Content-Type': 'text/plain'});res.write(“Start Hello"); res.end('Hello World\n');})

when ‘stuff’ happens my function firesI get a request object and a response objectI write to the response object header HTTP status

200 (Standard response for successful HTTP requests) and content-type ‘text/plain’

We make changes to the response object and then these are transmitted when we call: esponse.end();

Page 11: Scalable network applications, event-driven - Node JS

Basic HTTP ServerThis line requires the http module that ships with Node.js and

makes it accessible through the variable http.var http = require("http");

server = http.createServer(function(request, response) {response.writeHead(200, {"Content-Type": "text/plain"});response.write("Hello World");response.end();

}).listen(8888,”127.0.0.1”);

We pass a function into the server which it uses to handle all incoming requests.

When ‘stuff’ happens call this anonymous functionListen on port 8888 of the ip 127.0.0.1

Page 12: Scalable network applications, event-driven - Node JS

http.ServerRequest ObjectWhen listening for request events, the callback

gets an http.ServerRequest object as the first argument. This object has methods and properties:

req.url: This property contains the requested URL as a string. It does not contain the schema, hostname, or port, but it contains everything after that.

req.method: This contains the HTTP method used on the request. It can be, for example, GET, POST, DELETE, or HEAD.

req.headers: This contains an object with a property for every HTTP header on the request.

Page 13: Scalable network applications, event-driven - Node JS

http.ServerResponse ObjectWriting headers: res.writeHead(status, headers)Changing or setting a header res.setHeader(name, value);Writing a Piece of the Response Body:

res.write('Hello');or use an existing buffer:

var buffer = new Buffer('Hello World');res.write(buffer);

Streaming a mp4var fs = require('fs');require('http').createServer(function(req, res) {

res.writeHead(200, {'Content-Type': 'video/mp4'});var rs = fs.createReadStream('test.mp4');rs.pipe(res);

}).listen(4000);

Page 14: Scalable network applications, event-driven - Node JS

Basic node JS Module var mysql = require('mysql'); var connection = mysql.createConnection({ host : 'localhost', user : 'nod', password : 'nodejs', database : "test" });

function connectDatabase() { connection.connect(); console.log("db connected"); }

//insert data to database and call the function received function insertDatabase( data , callback ) { connection.query('INSERT INTO users (user) VALUES (?)',[data.clientName], function ( err, result ) { if (err) throw err; //calling callback function from server-chat.js callback ( result.insertId ); }); }

exports.startDatabase = connectDatabase;

exports.insertDatabase = insertDatabase;;

Page 15: Scalable network applications, event-driven - Node JS

ExampleFree Spark implementation:

http://10.182.39.2/

Page 16: Scalable network applications, event-driven - Node JS

Cosmin Mereuta