Scalable network applications, event-driven - Node JS
-
Upload
cosmin-mereuta -
Category
Technology
-
view
389 -
download
3
Transcript of Scalable network applications, event-driven - Node JS
JavaScript with nodeJs
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�
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.
What can NodeJS be used for?Network servers (HTTP, messaging)API backendsReal time applicationsStreaming dataWeb sitesBots
Typical architecture
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
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
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
Blocking vs Non-Blocking flow
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();
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
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.
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);
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;;
ExampleFree Spark implementation:
http://10.182.39.2/
Cosmin Mereuta