node.js introduction

28
Node.js Kelum Senanayake

Upload: kelum-senanayake

Post on 17-Jul-2015

211 views

Category:

Technology


0 download

TRANSCRIPT

Node.js

K e l u m S e n a n a y a k e

Introduction

History

• First published for Linux use in 2009

• Original author: Ryan Dahl

• npm, a package manager for Node.js libraries, was introduced in 2011

• In June 2011, Microsoft partnered with Joyent to create a native Windows version of Node.js

• Used by Groupon, SAP, LinkedIn, Microsoft, Yahoo!, Walmart, Rakuten, PayPal, Voxer, GoDaddy …

What is Node.js

• Node is a platform for JavaScript applications

• Node uses V8, the virtual machine that powers Google Chrome

• Node is

– Built on JavaScript

– Evented and asynchronous

– DIRTy by default

Built on JavaScript

• JavaScript is the world’s most popular programming language

• Developers can write web applications (client & server) in one language

• JSON is a very popular data interchange format today and is native to JavaScript

• JavaScript is the language used in various NoSQL databases

Asynchronous and evented

• Node is event-driven (uses an event loop) and non-blocking when handling I/O (uses asynchronous I/O)

• Example blocking code from PHP

• In Node, I/O is almost always performed outside of the main event loop, allowing the server to stay efficient and responsive

$result = mysql_query('SELECT * FROM myTable');

print_r($result);

Designed for data-intensive real-time applications

• DIRT : data-intensive real-time

• https://browserling.com/

• Node tries to keep consistency between the browser and the server by re-implementing common host objects:

– Timer API (for example, setTimeout)

– Console API (for example, console.log)

• Also includes a core set of modules for many types of network and file I/O.

– HTTP, TLS, HTTPS, filesystem (POSIX), Datagram (UDP), and NET (TCP).

• The core is intentionally small, low-level, and uncomplicated, including just the building blocks for I/O-based applications.

– Ex: HTTP parser consisting of roughly 1,500 lines of optimized C code.

Hello World HTTP server

var http = require('http');

var server = http.createServer();

server.on('request', function (req, res) {

res.writeHead(200, {'Content-Type': 'text/plain'});

res.end('Hello World\n');

});

server.listen(3000);

console.log('Server running at http://localhost:3000/');

Organizing and reusing Node functionality

Create Modules

• Modules can either be single files or directories containing one or more files

• Create a file that defines properties on the exports object with any kind of data, such as strings, objects, and functions

currency.js var singaporeDollar = 0.80;

function roundTwoDecimals(amount) {

return Math.round(amount * 100) / 100;

}

exports.singDollerToUS = function(singDoller) {

return roundTwoDecimals(singDoller *

singaporeDollar);

}

exports.USToSingDoller = function(us) {

return roundTwoDecimals(us / singaporeDollar);

}

test-currency.js

var currency = require('./currency');

console.log('50 Singapore dollars equals this amount

of US dollars:');

console.log(currency.singDollerToUS(50));

console.log('30 US dollars equals this amount of

Singapore dollars:');

console.log(currency.USToSingDoller(30));

currency-v2.js

module.exports = {

singDollerToUS : function(singDoller) {

return roundTwoDecimals(singDoller * singaporeDollar);

},

USToSingDoller : function(us) {

return roundTwoDecimals(us / singaporeDollar);

},

}

var singaporeDollar = 0.80;

function roundTwoDecimals(amount) {

return Math.round(amount * 100) / 100;

}

currency-v3.js var Currency = function(singaporeDollar) {

this.singaporeDollar = singaporeDollar;

}

Currency.prototype.roundTwoDecimals = function(amount) {

return Math.round(amount * 100) / 100;

}

Currency.prototype.singDollerToUS = function(singDoller) {

return this.roundTwoDecimals(singDoller *

this.singaporeDollar);

}

Currency.prototype.USToSingDoller = function(us) {

return this.roundTwoDecimals(us / this.singaporeDollar);

}

module.exports = Currency;

var Currency = require('./currency-v3');

var singDollar = 0.80;

var currency = new Currency(singDollar);

console.log(currency. singDollerToUS(50));

Reusing modules using node_modules

• Useful for code you’d like to reuse between applications or share with others

• Allows modules to be required without knowing their location in the file system

Asynchronous programming techniques

The two model of Async Processing

• Callbacks generally define logic for one-off responses.

– Ex: perform a database query

• Event listeners, are essentially callbacks that are associated with a conceptual entity (an event).

– Respond to repeating events

– EX: HTTP server emits a request event when an HTTP request is made

Handling one-off events with callbacks

• A callback is a function, passed as an argument to an asynchronous function

• It describes what to do after the asynchronous operation has completed

var fs = require('fs');

fs.readFile('./resource.json', function (er, data) {

console.log(data);

});

Callback function

The Node convention for asynchronous callbacks

• Most Node built-in modules use callbacks with two arguments

– First argument is for an error, should one occur.

often abbreviated as er or err

– Second argument is for the results

var fs = require('fs');

fs.readFile('./titles.json', function(er, data) {

if (er) throw er;

// do something with data if no error has occurred

});

Handling repeating events with event emitters

• Event emitters fire events and include the ability to handle them when triggered

• Events are handled through the use of listeners

• A listener is the association of an event with a callback function that gets triggered each time the event occurs

var net = require('net');

var server = net.createServer(function(socket) {

socket.on('data', function(data) {

socket.write(data);

});

});

server.listen(8888);

data events handled whenever new data has been read

Using the on method to respond to events

Responding to an event that should only occur once

var net = require('net');

var server = net.createServer(function(socket) {

socket.once ('data', function(data) {

socket.write(data);

});

});

server.listen(8888);

data event will only be handled once

References

• [1] Mike Cantelon, Marc Harter, T.J. Holowaychuk and Nathan Rajlich, Node.js in Action, 1st ed. Manning Publications, 2014.

• [2] "Node.js - Wikipedia, the free encyclopedia." [Online]. Available: http://en.wikipedia.org/wiki/Node.js. [Accessed: 26-Apr-2015].

Q & A