SlideShare une entreprise Scribd logo
1  sur  81
Télécharger pour lire hors ligne
@somkiat
Node.js goal
● Provide easy way to build scalable network
application
Node.js not
● Another Web framework
● For beginner
● Multi-thread
Node.js is
● Server side JavaScript
● Fun !!!
Node.js why
● Non Blocking I/O
● V8 Javascript Engine
● Single Thread with Event Loop
● 40,025 modules
● Windows, Linux, Mac
● 1 Language for Frontend and Backend
● Active community
Node.js for
● Web application
● Websocket server
● Ad server
● Proxy server
● Streaming server
● Fast file upload client
● Any Real-time data apps
● Anything with high I/O
Who use Node.js
http://nodejs.org/industry/
Node.js installation
● Download package from Nodejs.org
Demo :: Hello World
● Create file hello.js
console.log( “Hello World” );
● Run with Node
$node hello.js
>> Hello World
Blocking vs Non-Blocking
● Topic :: Read data from file and show data
Blocking
● Read data from file
● Show data
● Do other tasks
var data = fs.readFileSync( “test.txt” );
console.log( data );
console.log( “Do other tasks” );
http://nodejs.org/api/fs.html
Non-Blocking
● Read data from file
○ When read data completed, show data
● Do other tasks
fs.readFile( “test.txt”, function( err, data ) {
console.log(data);
});
console.log(“Do other tasks”);
Callback
Callback syntax
fs.readFile( “test.txt”, function( err, data ) {
console.log(data);
});
fs.readFile( “test.txt”, callback )
var callback = function( err, data ) {
console.log(data);
}
As same as
Blocking vs Non-Blocking
var callback = function(err, data) {
console.log(data);
}
fs.readFile("test.txt", callback);
fs.readFile("test2.txt", callback);
Blocking vs Non-Blocking
Recommended modules
● Async
○ https://github.com/caolan/async
● Step
○ https://github.com/creationix/step
Demo :: Basic HTTP
#hello_server_01.js
var http = require('http');
http.createServer( function (req, res) {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('Hello Worldn');
}).listen(1337, '127.0.0.1');
console.log('Server running at http://127.0.0.1:1337');
Demo :: Basic HTTP
$node hello_server_01.js
>Server running at http://127.0.0.1:1337/
Check result from browser http://127.0.0.1:1337
Demo :: Basic HTTP ( Refactor )
var http = require('http');
var server = http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('Hello Worldn');
});
server.listen(1337, ‘127.0.0.1’);
console.log('Server running at http://127.0.0.1:1337/');
Event Loop ?
var http = require('http');
var server = http.createServer(function (req, res) {
….
});
server.listen(1337, ‘127.0.0.1’);
Event Loop ?
var http = require('http');
var server = http.createServer(function (req, res) {
….
});
server.listen(1337, ‘127.0.0.1’);
Start Event Loop
Event Loop ?
var http = require('http');
var server = http.createServer(function (req, res) {
….
});
server.listen(1337, ‘127.0.0.1’);
Checking
Event
Known Event
Request
Run callback
Event Loop
Checking
Event
Known Event
Request
Event
Close
Connection
Request
Handle Event
var http = require('http');
var server = http.createServer();
server.on('request', function(req, res){
res.write('Got requestn');
res.end();
});
server.listen(1337, ‘127.0.0.1’);
http://nodejs.org/api/http.html
Demo :: Echo server
var server = http.createServer( function(req, res) {
res.writeHead(200);
req.on('data', function(data) {
res.write(data);
});
req.on('end', function(){
res.end();
});
});
Demo :: Echo server
$curl -d "somkiat" http://localhost:1337
Demo :: Echo server
var server = http.createServer( function(req, res) {
res.writeHead(200);
req.on('data', function(data) {
res.write(data);
});
req.on('end', function(){
res.end();
});
});
Pipe data from
request to response
Demo :: Echo server + Pipe
var server = http.createServer( function(req, res) {
res.writeHead(200);
req.pipe(res);
});
Demo :: Upload file
http.createServer(function(req, res) {
var newFile = fs.createWriteStream("uploaded.txt");
req.pipe(newFile);
req.on('end', function() {
res.end('uploaded!');
});
}).listen(1337);
Create file on server
and pipe data to file
Demo :: Upload file
http.createServer(function(req, res) {
var newFile = fs.createWriteStream("uploaded.txt");
req.pipe(newFile);
req.on('end', function() {
res.end('uploaded!');
});
}).listen(1337);
Handle end event on
request
Demo :: Upload file
$curl --upload-file test.txt http://localhost:1337
Demo :: Upload file with progress
Node.js Modules
● https://npmjs.org/
● # of modules = 40,025
Install module
$npm install <module name>
Using module
var http = require(‘http’);
var fs = require(‘fs’);
var express = require(‘express’);
Working with Express
● http://expressjs.com
Working with Express
● Inspire from Sinatra
● Fast
● Flexible
● Simple
Installation express
$npm install express
Demo :: Express
var express = require('express');
var app = express();
app.get('/', function (req, res) {
res.setHeader('Content-Type', 'text/plain');
res.end('Hello, world!');
});
app.listen(1337);
console.log('Listening on port 1337');
Demo :: Manage package
$npm init
$npm info express version
Demo :: package.json
{
"name": "hello-world",
"description": "hello world test app",
"version": "0.0.1",
"private": true,
"dependencies": {
"express": "3.3.x"
}
}
Demo :: Install and run
$npm install
$node http_express.js
Develop REST API
● REST = REpresentational State Transfer
● Not new technology
● Architectural style for client-server
http://en.wikipedia.org/wiki/Representational_state_transfer
Goals of REST
● General interface
● Scalability of component interface
● Reduce latency
● Encapsulate legacy system
SOA is DEAD!!
SOA is DEAD !!!
http://www.zdnet.com/blog/service-oriented/you-cant-beat-the-dead-soa-horse/3708
HTTP Method
● GET
● POST
● PUT
● DELETE
HTTP Method with CRUD
● POST => Create
● GET => Read
● PUT => Update
● DELETE => Delete
Demo :: REST with JSON
app.get('/', function (req, res) {
res.json(persons);
});
app.post('/', function (req, res) {
res.json(persons);
});
Demo :: REST with JSON
app.put('/', function (req, res) {
res.json(persons);
});
app.delete('/', function (req, res) {
res.json(persons);
});
Demo :: Refactoring
app.get('/', callback);
var callback = function getData(req, res) {
res.json(persons);
}
Working with Persistence
● MySQL
● MongoDB
● Redis
Working with Persistence
REST API Person service
MySQL
Redis
MongoDB
REST API
Method URL Action
GET / Get all person
GET /person/3 Get person by id=3
POST /person Add new person
PUT /person Update person by id
DELETE /person/3 Delete person by id=3
Demo :: REST API
var express = require('express');
var service_person = require('./service_person')
var app = express();
app.get('/', service_person.all);
app.get('/person/:id', service_person.one);
app.post('/person', service_person.insert);
app.put('/person', service_person.update);
app.get('/person/:id', service_person.delete);
app.listen(process.env.PORT || 1337);
Working with MySQL
● RDBMS
● Module => see in npmjs.org ( a lot !!!! )
○ "mysql": "2.0.0-alpha9"
Design Table
● Table name = person
○ Column
■ id
■ name
■ gender
Demo :: Connect to MySQL
var mysql = require('mysql');
var connection = mysql.createConnection(
{
host: <db server>,
user: <username>,
password: <password>,
database: <database name>
}
);
Demo :: Retrieve all data
connection.query('select * from person',
function(err, rows, fields) {
res.contentType('application/json');
res.write(JSON.stringify(rows));
res.end();
}
);
Demo :: Retrieve data with criteria
var sql = 'select * from person where id=?';
connection.query( sql, [id],
function(err, rows, fields) {
res.contentType('application/json');
res.write(JSON.stringify(rows));
res.end();
}
);
Demo :: Create new data
var sql = 'insert into person (name, gender)
values (?, ?)
';
connection.query( sql, [name, gender],
function(err, rows, fields) {
res.json(true);
}
);
Working with MongoDB
● NoSQL
● Document-oriented stoarage
● Keep data in BSON format
● http://www.mongodb.org/
● Module => see in npmjs.org ( a lot !!!! )
○ "redis": "0.8.4"
http://en.wikipedia.org/wiki/BSON
Start MongoDB server
$mongod.exe --dbpath /some/data/path
Demo :: Connect to MongoDB
var mongo = require('mongodb');
var Server = mongo.Server,
var server = new Server(
'localhost',
27017,
{auto_reconnect: true}
);
db = new Db('persons', server);
Demo :: Connect to MongoDB
db.open(function(err, db) {
if(!err) {
db.collection('persons', {strict:true},
function(err, collection) {
if (err) {
populateDB();
}
});
}
Demo :: Retrieve all data
exports.all = function(req, res){
db.collection('persons', function(err, collection) {
collection.find().toArray(function(err, persons) {
res.send(persons);
});
});
};
Demo :: Retrieve data by id
exports.one = function(req, res){
var personId = req.params.id;
db.collection('persons', function(err, collection) {
collection.findOne(
{'_id':new BSON.ObjectID(personId)},
function(err, person) {
res.send(person);
});
});
};
Demo :: Create new data
exports.insert = function(req, res){
db.collection('persons', function(err, collection) {
collection.insert( person, {safe:true},
function(err, result) {
});
});
});
Demo :: Update data
exports.insert = function(req, res){
db.collection('persons', function(err, collection) {
collection.update( {
'_id':new BSON.ObjectID( personId )},
updatePerson,
{safe:true},
function(err, result) {
});
});
});
Demo :: Delete data by id
exports.insert = function(req, res){
db.collection('persons', function(err, collection) {
collection.remove( {
'_id':new BSON.ObjectID( personId )},
{safe:true},
function(err, result) {
});
});
});
Design Document
● Collection = persons
● Document structure
○ name
○ gender
Working with Redis
● NoSQL
● Key-value data store
● http://redis.io
● Module => see in npmjs.org ( a lot !!!! )
○ "redis": "0.8.4"
Install Redis
● Download from http://redis.io/
● For Windows OS
○ https://github.com/dmajkic/redis/downloads
Start Redis server
$redis-server
Let’s fun with Redis
$redis-cli
Design Key-Value
● Key = person_list
○ type = List
○ value = id
● Key = id
○ type = Hash
■ id = <id>
■ name = <name>
■ gender = <gender>
Demo :: Connect to Redis
var redis = require('redis');
var connection = redis.createClient(
{
host: 'localhost',
port: '6379'
}
);
Favorite Modules
● express
● underscore
● request
● async
● mysql
● Find more in npmjs.org
Another project like Node.js
● Vert.x => Polygot programming
● Akka => Scala and Java
● Tornado => Python
● Libevent => C
● EventMachine => Ruby
Book
Resources
● Sourcecode for demo https://github.
com/up1/demo_nodejs
● https://npmjs.org
● http://nodejs.org/
● http://callbackhell.com/
● http://nodeframework.com/
Q/A

Contenu connexe

Tendances

Java script at backend nodejs
Java script at backend   nodejsJava script at backend   nodejs
Java script at backend nodejsAmit Thakkar
 
node.js: Javascript's in your backend
node.js: Javascript's in your backendnode.js: Javascript's in your backend
node.js: Javascript's in your backendDavid Padbury
 
Writing robust Node.js applications
Writing robust Node.js applicationsWriting robust Node.js applications
Writing robust Node.js applicationsTom Croucher
 
A language for the Internet: Why JavaScript and Node.js is right for Internet...
A language for the Internet: Why JavaScript and Node.js is right for Internet...A language for the Internet: Why JavaScript and Node.js is right for Internet...
A language for the Internet: Why JavaScript and Node.js is right for Internet...Tom Croucher
 
Node.js - A practical introduction (v2)
Node.js  - A practical introduction (v2)Node.js  - A practical introduction (v2)
Node.js - A practical introduction (v2)Felix Geisendörfer
 
Node.js introduction
Node.js introductionNode.js introduction
Node.js introductionParth Joshi
 
RESTful API In Node Js using Express
RESTful API In Node Js using Express RESTful API In Node Js using Express
RESTful API In Node Js using Express Jeetendra singh
 
Event-driven IO server-side JavaScript environment based on V8 Engine
Event-driven IO server-side JavaScript environment based on V8 EngineEvent-driven IO server-side JavaScript environment based on V8 Engine
Event-driven IO server-side JavaScript environment based on V8 EngineRicardo Silva
 
Understanding the Node.js Platform
Understanding the Node.js PlatformUnderstanding the Node.js Platform
Understanding the Node.js PlatformDomenic Denicola
 
A million connections and beyond - Node.js at scale
A million connections and beyond - Node.js at scaleA million connections and beyond - Node.js at scale
A million connections and beyond - Node.js at scaleTom Croucher
 
Original slides from Ryan Dahl's NodeJs intro talk
Original slides from Ryan Dahl's NodeJs intro talkOriginal slides from Ryan Dahl's NodeJs intro talk
Original slides from Ryan Dahl's NodeJs intro talkAarti Parikh
 
Building your first Node app with Connect & Express
Building your first Node app with Connect & ExpressBuilding your first Node app with Connect & Express
Building your first Node app with Connect & ExpressChristian Joudrey
 
Node.js Patterns for Discerning Developers
Node.js Patterns for Discerning DevelopersNode.js Patterns for Discerning Developers
Node.js Patterns for Discerning Developerscacois
 

Tendances (20)

Nodejs - A quick tour (v6)
Nodejs - A quick tour (v6)Nodejs - A quick tour (v6)
Nodejs - A quick tour (v6)
 
Java script at backend nodejs
Java script at backend   nodejsJava script at backend   nodejs
Java script at backend nodejs
 
node.js: Javascript's in your backend
node.js: Javascript's in your backendnode.js: Javascript's in your backend
node.js: Javascript's in your backend
 
Writing robust Node.js applications
Writing robust Node.js applicationsWriting robust Node.js applications
Writing robust Node.js applications
 
A language for the Internet: Why JavaScript and Node.js is right for Internet...
A language for the Internet: Why JavaScript and Node.js is right for Internet...A language for the Internet: Why JavaScript and Node.js is right for Internet...
A language for the Internet: Why JavaScript and Node.js is right for Internet...
 
Node.js - A practical introduction (v2)
Node.js  - A practical introduction (v2)Node.js  - A practical introduction (v2)
Node.js - A practical introduction (v2)
 
Node.js introduction
Node.js introductionNode.js introduction
Node.js introduction
 
RESTful API In Node Js using Express
RESTful API In Node Js using Express RESTful API In Node Js using Express
RESTful API In Node Js using Express
 
Event-driven IO server-side JavaScript environment based on V8 Engine
Event-driven IO server-side JavaScript environment based on V8 EngineEvent-driven IO server-side JavaScript environment based on V8 Engine
Event-driven IO server-side JavaScript environment based on V8 Engine
 
Understanding the Node.js Platform
Understanding the Node.js PlatformUnderstanding the Node.js Platform
Understanding the Node.js Platform
 
Node.js - A Quick Tour II
Node.js - A Quick Tour IINode.js - A Quick Tour II
Node.js - A Quick Tour II
 
hacking with node.JS
hacking with node.JShacking with node.JS
hacking with node.JS
 
Node ppt
Node pptNode ppt
Node ppt
 
A million connections and beyond - Node.js at scale
A million connections and beyond - Node.js at scaleA million connections and beyond - Node.js at scale
A million connections and beyond - Node.js at scale
 
Introduction Node.js
Introduction Node.jsIntroduction Node.js
Introduction Node.js
 
Nodejs - A quick tour (v4)
Nodejs - A quick tour (v4)Nodejs - A quick tour (v4)
Nodejs - A quick tour (v4)
 
Nodejs - A quick tour (v5)
Nodejs - A quick tour (v5)Nodejs - A quick tour (v5)
Nodejs - A quick tour (v5)
 
Original slides from Ryan Dahl's NodeJs intro talk
Original slides from Ryan Dahl's NodeJs intro talkOriginal slides from Ryan Dahl's NodeJs intro talk
Original slides from Ryan Dahl's NodeJs intro talk
 
Building your first Node app with Connect & Express
Building your first Node app with Connect & ExpressBuilding your first Node app with Connect & Express
Building your first Node app with Connect & Express
 
Node.js Patterns for Discerning Developers
Node.js Patterns for Discerning DevelopersNode.js Patterns for Discerning Developers
Node.js Patterns for Discerning Developers
 

En vedette

Практика разрешения судебных споров, связанных с персональными данными
Практика разрешения судебных споров, связанных с персональными даннымиПрактика разрешения судебных споров, связанных с персональными данными
Практика разрешения судебных споров, связанных с персональными даннымиNatasha Khramtsovsky
 
PROEXPOSURE Photos Religion
PROEXPOSURE Photos ReligionPROEXPOSURE Photos Religion
PROEXPOSURE Photos ReligionPROEXPOSURE CIC
 
Halálugrás telefonnal
Halálugrás telefonnalHalálugrás telefonnal
Halálugrás telefonnalguestffe92f
 
Presentation1
Presentation1Presentation1
Presentation1mrounds5
 
Cliftons Powerpoint
Cliftons PowerpointCliftons Powerpoint
Cliftons Powerpointmrounds5
 
Эквивалентность бумажных и электронных документов
Эквивалентность бумажных и электронных документовЭквивалентность бумажных и электронных документов
Эквивалентность бумажных и электронных документовNatasha Khramtsovsky
 
Fmc Ver 1.3 June 27 2007
Fmc Ver 1.3 June 27 2007Fmc Ver 1.3 June 27 2007
Fmc Ver 1.3 June 27 2007Jack Brown
 
В достаточной ли мере развивается законодательная и нормативно-правовая база ...
В достаточной ли мере развивается законодательная и нормативно-правовая база ...В достаточной ли мере развивается законодательная и нормативно-правовая база ...
В достаточной ли мере развивается законодательная и нормативно-правовая база ...Natasha Khramtsovsky
 
Stroke Recognition And Treatment
Stroke Recognition And TreatmentStroke Recognition And Treatment
Stroke Recognition And Treatmentdstroup461
 
Законодательство о свободе доступа к государственной информации: последствия ...
Законодательство о свободе доступа к государственной информации: последствия ...Законодательство о свободе доступа к государственной информации: последствия ...
Законодательство о свободе доступа к государственной информации: последствия ...Natasha Khramtsovsky
 
Minette's Snowman
Minette's SnowmanMinette's Snowman
Minette's Snowmanjbirdink
 

En vedette (20)

Практика разрешения судебных споров, связанных с персональными данными
Практика разрешения судебных споров, связанных с персональными даннымиПрактика разрешения судебных споров, связанных с персональными данными
Практика разрешения судебных споров, связанных с персональными данными
 
Jail TV: Crimineel goede televisie
Jail TV: Crimineel goede televisieJail TV: Crimineel goede televisie
Jail TV: Crimineel goede televisie
 
PROEXPOSURE Photos Religion
PROEXPOSURE Photos ReligionPROEXPOSURE Photos Religion
PROEXPOSURE Photos Religion
 
Economics 2 2
Economics 2 2Economics 2 2
Economics 2 2
 
Halálugrás telefonnal
Halálugrás telefonnalHalálugrás telefonnal
Halálugrás telefonnal
 
Presentation1
Presentation1Presentation1
Presentation1
 
jMeter101
jMeter101jMeter101
jMeter101
 
Cliftons Powerpoint
Cliftons PowerpointCliftons Powerpoint
Cliftons Powerpoint
 
Эквивалентность бумажных и электронных документов
Эквивалентность бумажных и электронных документовЭквивалентность бумажных и электронных документов
Эквивалентность бумажных и электронных документов
 
Fmc Ver 1.3 June 27 2007
Fmc Ver 1.3 June 27 2007Fmc Ver 1.3 June 27 2007
Fmc Ver 1.3 June 27 2007
 
В достаточной ли мере развивается законодательная и нормативно-правовая база ...
В достаточной ли мере развивается законодательная и нормативно-правовая база ...В достаточной ли мере развивается законодательная и нормативно-правовая база ...
В достаточной ли мере развивается законодательная и нормативно-правовая база ...
 
Stilte, Rust en Ruimte Kempen Def Trefdag
Stilte, Rust en Ruimte Kempen Def TrefdagStilte, Rust en Ruimte Kempen Def Trefdag
Stilte, Rust en Ruimte Kempen Def Trefdag
 
Stroke Recognition And Treatment
Stroke Recognition And TreatmentStroke Recognition And Treatment
Stroke Recognition And Treatment
 
Законодательство о свободе доступа к государственной информации: последствия ...
Законодательство о свободе доступа к государственной информации: последствия ...Законодательство о свободе доступа к государственной информации: последствия ...
Законодательство о свободе доступа к государственной информации: последствия ...
 
Climate Impacts Ana
Climate  Impacts AnaClimate  Impacts Ana
Climate Impacts Ana
 
Energetic
EnergeticEnergetic
Energetic
 
Public relations?!
Public relations?!Public relations?!
Public relations?!
 
Karel Vanrietvelde
Karel VanrietveldeKarel Vanrietvelde
Karel Vanrietvelde
 
Jered
JeredJered
Jered
 
Minette's Snowman
Minette's SnowmanMinette's Snowman
Minette's Snowman
 

Similaire à Introduction to Node.js

Introduction to REST API with Node.js
Introduction to REST API with Node.jsIntroduction to REST API with Node.js
Introduction to REST API with Node.jsYoann Gotthilf
 
Nodejs and WebSockets
Nodejs and WebSocketsNodejs and WebSockets
Nodejs and WebSocketsGonzalo Ayuso
 
soft-shake.ch - Hands on Node.js
soft-shake.ch - Hands on Node.jssoft-shake.ch - Hands on Node.js
soft-shake.ch - Hands on Node.jssoft-shake.ch
 
Scalable network applications, event-driven - Node JS
Scalable network applications, event-driven - Node JSScalable network applications, event-driven - Node JS
Scalable network applications, event-driven - Node JSCosmin Mereuta
 
Getting started with node JS
Getting started with node JSGetting started with node JS
Getting started with node JSHamdi Hmidi
 
An Overview of Node.js
An Overview of Node.jsAn Overview of Node.js
An Overview of Node.jsAyush Mishra
 
Practical Use of MongoDB for Node.js
Practical Use of MongoDB for Node.jsPractical Use of MongoDB for Node.js
Practical Use of MongoDB for Node.jsasync_io
 
Introduction to Node.js Platform
Introduction to Node.js PlatformIntroduction to Node.js Platform
Introduction to Node.js PlatformNaresh Chintalcheru
 
Introduction to Node.js
Introduction to Node.jsIntroduction to Node.js
Introduction to Node.jsVikash Singh
 
Intro to node and mongodb 1
Intro to node and mongodb   1Intro to node and mongodb   1
Intro to node and mongodb 1Mohammad Qureshi
 
Introduction to node.js
Introduction to node.jsIntroduction to node.js
Introduction to node.jsAdrien Guéret
 
Node.js: The What, The How and The When
Node.js: The What, The How and The WhenNode.js: The What, The How and The When
Node.js: The What, The How and The WhenFITC
 
Server Side Event Driven Programming
Server Side Event Driven ProgrammingServer Side Event Driven Programming
Server Side Event Driven ProgrammingKamal Hussain
 
Building and Scaling Node.js Applications
Building and Scaling Node.js ApplicationsBuilding and Scaling Node.js Applications
Building and Scaling Node.js ApplicationsOhad Kravchick
 

Similaire à Introduction to Node.js (20)

Introduction to REST API with Node.js
Introduction to REST API with Node.jsIntroduction to REST API with Node.js
Introduction to REST API with Node.js
 
Nodejs and WebSockets
Nodejs and WebSocketsNodejs and WebSockets
Nodejs and WebSockets
 
Node.js
Node.jsNode.js
Node.js
 
soft-shake.ch - Hands on Node.js
soft-shake.ch - Hands on Node.jssoft-shake.ch - Hands on Node.js
soft-shake.ch - Hands on Node.js
 
NodeJS
NodeJSNodeJS
NodeJS
 
Scalable network applications, event-driven - Node JS
Scalable network applications, event-driven - Node JSScalable network applications, event-driven - Node JS
Scalable network applications, event-driven - Node JS
 
Getting started with node JS
Getting started with node JSGetting started with node JS
Getting started with node JS
 
An Overview of Node.js
An Overview of Node.jsAn Overview of Node.js
An Overview of Node.js
 
Practical Use of MongoDB for Node.js
Practical Use of MongoDB for Node.jsPractical Use of MongoDB for Node.js
Practical Use of MongoDB for Node.js
 
Introduction to Node.js Platform
Introduction to Node.js PlatformIntroduction to Node.js Platform
Introduction to Node.js Platform
 
5.node js
5.node js5.node js
5.node js
 
node.js dao
node.js daonode.js dao
node.js dao
 
Introduction to Node.js
Introduction to Node.jsIntroduction to Node.js
Introduction to Node.js
 
Intro to node and mongodb 1
Intro to node and mongodb   1Intro to node and mongodb   1
Intro to node and mongodb 1
 
Introduction to node.js
Introduction to node.jsIntroduction to node.js
Introduction to node.js
 
Node.js: The What, The How and The When
Node.js: The What, The How and The WhenNode.js: The What, The How and The When
Node.js: The What, The How and The When
 
Event driven programming -- Node.JS
Event driven programming -- Node.JSEvent driven programming -- Node.JS
Event driven programming -- Node.JS
 
Intro to Node
Intro to NodeIntro to Node
Intro to Node
 
Server Side Event Driven Programming
Server Side Event Driven ProgrammingServer Side Event Driven Programming
Server Side Event Driven Programming
 
Building and Scaling Node.js Applications
Building and Scaling Node.js ApplicationsBuilding and Scaling Node.js Applications
Building and Scaling Node.js Applications
 

Plus de Somkiat Puisungnoen (20)

Next of Java 2022
Next of Java 2022Next of Java 2022
Next of Java 2022
 
Sck spring-reactive
Sck spring-reactiveSck spring-reactive
Sck spring-reactive
 
Part 2 :: Spring Boot testing
Part 2 :: Spring Boot testingPart 2 :: Spring Boot testing
Part 2 :: Spring Boot testing
 
vTalk#1 Microservices with Spring Boot
vTalk#1 Microservices with Spring BootvTalk#1 Microservices with Spring Boot
vTalk#1 Microservices with Spring Boot
 
Lesson learned from React native and Flutter
Lesson learned from React native and FlutterLesson learned from React native and Flutter
Lesson learned from React native and Flutter
 
devops
devops devops
devops
 
Angular :: basic tuning performance
Angular :: basic tuning performanceAngular :: basic tuning performance
Angular :: basic tuning performance
 
Shared code between projects
Shared code between projectsShared code between projects
Shared code between projects
 
Distributed Tracing
Distributed Tracing Distributed Tracing
Distributed Tracing
 
Manage data of service
Manage data of serviceManage data of service
Manage data of service
 
RobotFramework Meetup at Thailand #2
RobotFramework Meetup at Thailand #2RobotFramework Meetup at Thailand #2
RobotFramework Meetup at Thailand #2
 
Visual testing
Visual testingVisual testing
Visual testing
 
Cloud Native App
Cloud Native AppCloud Native App
Cloud Native App
 
Wordpress for Newbie
Wordpress for NewbieWordpress for Newbie
Wordpress for Newbie
 
Sck Agile in Real World
Sck Agile in Real WorldSck Agile in Real World
Sck Agile in Real World
 
Clean you code
Clean you codeClean you code
Clean you code
 
SCK Firestore at CNX
SCK Firestore at CNXSCK Firestore at CNX
SCK Firestore at CNX
 
Unhappiness Developer
Unhappiness DeveloperUnhappiness Developer
Unhappiness Developer
 
The Beauty of BAD code
The Beauty of  BAD codeThe Beauty of  BAD code
The Beauty of BAD code
 
React in the right way
React in the right wayReact in the right way
React in the right way
 

Dernier

Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Commit University
 
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxA Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxLoriGlavin3
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024Lonnie McRorey
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxNavinnSomaal
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenHervé Boutemy
 
Generative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information DevelopersGenerative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information DevelopersRaghuram Pandurangan
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity PlanDatabarracks
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr BaganFwdays
 
unit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptxunit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptxBkGupta21
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Mattias Andersson
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubKalema Edgar
 
What is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfWhat is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfMounikaPolabathina
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsPixlogix Infotech
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.Curtis Poe
 
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxPasskey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxLoriGlavin3
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek SchlawackFwdays
 
The State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxThe State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxLoriGlavin3
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024Stephanie Beckett
 

Dernier (20)

Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!
 
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxA Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024
 
DMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special EditionDMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special Edition
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptx
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache Maven
 
Generative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information DevelopersGenerative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information Developers
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity Plan
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan
 
unit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptxunit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptx
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding Club
 
What is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfWhat is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdf
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and Cons
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.
 
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxPasskey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
 
The State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxThe State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptx
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024
 

Introduction to Node.js

  • 2. Node.js goal ● Provide easy way to build scalable network application
  • 3. Node.js not ● Another Web framework ● For beginner ● Multi-thread
  • 4. Node.js is ● Server side JavaScript ● Fun !!!
  • 5. Node.js why ● Non Blocking I/O ● V8 Javascript Engine ● Single Thread with Event Loop ● 40,025 modules ● Windows, Linux, Mac ● 1 Language for Frontend and Backend ● Active community
  • 6. Node.js for ● Web application ● Websocket server ● Ad server ● Proxy server ● Streaming server ● Fast file upload client ● Any Real-time data apps ● Anything with high I/O
  • 8. Node.js installation ● Download package from Nodejs.org
  • 9. Demo :: Hello World ● Create file hello.js console.log( “Hello World” ); ● Run with Node $node hello.js >> Hello World
  • 10. Blocking vs Non-Blocking ● Topic :: Read data from file and show data
  • 11. Blocking ● Read data from file ● Show data ● Do other tasks var data = fs.readFileSync( “test.txt” ); console.log( data ); console.log( “Do other tasks” ); http://nodejs.org/api/fs.html
  • 12. Non-Blocking ● Read data from file ○ When read data completed, show data ● Do other tasks fs.readFile( “test.txt”, function( err, data ) { console.log(data); }); console.log(“Do other tasks”); Callback
  • 13. Callback syntax fs.readFile( “test.txt”, function( err, data ) { console.log(data); }); fs.readFile( “test.txt”, callback ) var callback = function( err, data ) { console.log(data); } As same as
  • 14. Blocking vs Non-Blocking var callback = function(err, data) { console.log(data); } fs.readFile("test.txt", callback); fs.readFile("test2.txt", callback);
  • 16. Recommended modules ● Async ○ https://github.com/caolan/async ● Step ○ https://github.com/creationix/step
  • 17. Demo :: Basic HTTP #hello_server_01.js var http = require('http'); http.createServer( function (req, res) { res.writeHead(200, {'Content-Type': 'text/plain'}); res.end('Hello Worldn'); }).listen(1337, '127.0.0.1'); console.log('Server running at http://127.0.0.1:1337');
  • 18. Demo :: Basic HTTP $node hello_server_01.js >Server running at http://127.0.0.1:1337/ Check result from browser http://127.0.0.1:1337
  • 19. Demo :: Basic HTTP ( Refactor ) var http = require('http'); var server = http.createServer(function (req, res) { res.writeHead(200, {'Content-Type': 'text/plain'}); res.end('Hello Worldn'); }); server.listen(1337, ‘127.0.0.1’); console.log('Server running at http://127.0.0.1:1337/');
  • 20. Event Loop ? var http = require('http'); var server = http.createServer(function (req, res) { …. }); server.listen(1337, ‘127.0.0.1’);
  • 21. Event Loop ? var http = require('http'); var server = http.createServer(function (req, res) { …. }); server.listen(1337, ‘127.0.0.1’); Start Event Loop
  • 22. Event Loop ? var http = require('http'); var server = http.createServer(function (req, res) { …. }); server.listen(1337, ‘127.0.0.1’); Checking Event Known Event Request Run callback
  • 24. Handle Event var http = require('http'); var server = http.createServer(); server.on('request', function(req, res){ res.write('Got requestn'); res.end(); }); server.listen(1337, ‘127.0.0.1’); http://nodejs.org/api/http.html
  • 25. Demo :: Echo server var server = http.createServer( function(req, res) { res.writeHead(200); req.on('data', function(data) { res.write(data); }); req.on('end', function(){ res.end(); }); });
  • 26. Demo :: Echo server $curl -d "somkiat" http://localhost:1337
  • 27. Demo :: Echo server var server = http.createServer( function(req, res) { res.writeHead(200); req.on('data', function(data) { res.write(data); }); req.on('end', function(){ res.end(); }); }); Pipe data from request to response
  • 28. Demo :: Echo server + Pipe var server = http.createServer( function(req, res) { res.writeHead(200); req.pipe(res); });
  • 29. Demo :: Upload file http.createServer(function(req, res) { var newFile = fs.createWriteStream("uploaded.txt"); req.pipe(newFile); req.on('end', function() { res.end('uploaded!'); }); }).listen(1337); Create file on server and pipe data to file
  • 30. Demo :: Upload file http.createServer(function(req, res) { var newFile = fs.createWriteStream("uploaded.txt"); req.pipe(newFile); req.on('end', function() { res.end('uploaded!'); }); }).listen(1337); Handle end event on request
  • 31. Demo :: Upload file $curl --upload-file test.txt http://localhost:1337
  • 32. Demo :: Upload file with progress
  • 35. Using module var http = require(‘http’); var fs = require(‘fs’); var express = require(‘express’);
  • 36. Working with Express ● http://expressjs.com
  • 37. Working with Express ● Inspire from Sinatra ● Fast ● Flexible ● Simple
  • 39. Demo :: Express var express = require('express'); var app = express(); app.get('/', function (req, res) { res.setHeader('Content-Type', 'text/plain'); res.end('Hello, world!'); }); app.listen(1337); console.log('Listening on port 1337');
  • 40. Demo :: Manage package $npm init $npm info express version
  • 41. Demo :: package.json { "name": "hello-world", "description": "hello world test app", "version": "0.0.1", "private": true, "dependencies": { "express": "3.3.x" } }
  • 42. Demo :: Install and run $npm install $node http_express.js
  • 43. Develop REST API ● REST = REpresentational State Transfer ● Not new technology ● Architectural style for client-server http://en.wikipedia.org/wiki/Representational_state_transfer
  • 44. Goals of REST ● General interface ● Scalability of component interface ● Reduce latency ● Encapsulate legacy system
  • 46. SOA is DEAD !!! http://www.zdnet.com/blog/service-oriented/you-cant-beat-the-dead-soa-horse/3708
  • 47. HTTP Method ● GET ● POST ● PUT ● DELETE
  • 48. HTTP Method with CRUD ● POST => Create ● GET => Read ● PUT => Update ● DELETE => Delete
  • 49. Demo :: REST with JSON app.get('/', function (req, res) { res.json(persons); }); app.post('/', function (req, res) { res.json(persons); });
  • 50. Demo :: REST with JSON app.put('/', function (req, res) { res.json(persons); }); app.delete('/', function (req, res) { res.json(persons); });
  • 51. Demo :: Refactoring app.get('/', callback); var callback = function getData(req, res) { res.json(persons); }
  • 52. Working with Persistence ● MySQL ● MongoDB ● Redis
  • 53. Working with Persistence REST API Person service MySQL Redis MongoDB
  • 54. REST API Method URL Action GET / Get all person GET /person/3 Get person by id=3 POST /person Add new person PUT /person Update person by id DELETE /person/3 Delete person by id=3
  • 55. Demo :: REST API var express = require('express'); var service_person = require('./service_person') var app = express(); app.get('/', service_person.all); app.get('/person/:id', service_person.one); app.post('/person', service_person.insert); app.put('/person', service_person.update); app.get('/person/:id', service_person.delete); app.listen(process.env.PORT || 1337);
  • 56. Working with MySQL ● RDBMS ● Module => see in npmjs.org ( a lot !!!! ) ○ "mysql": "2.0.0-alpha9"
  • 57. Design Table ● Table name = person ○ Column ■ id ■ name ■ gender
  • 58. Demo :: Connect to MySQL var mysql = require('mysql'); var connection = mysql.createConnection( { host: <db server>, user: <username>, password: <password>, database: <database name> } );
  • 59. Demo :: Retrieve all data connection.query('select * from person', function(err, rows, fields) { res.contentType('application/json'); res.write(JSON.stringify(rows)); res.end(); } );
  • 60. Demo :: Retrieve data with criteria var sql = 'select * from person where id=?'; connection.query( sql, [id], function(err, rows, fields) { res.contentType('application/json'); res.write(JSON.stringify(rows)); res.end(); } );
  • 61. Demo :: Create new data var sql = 'insert into person (name, gender) values (?, ?) '; connection.query( sql, [name, gender], function(err, rows, fields) { res.json(true); } );
  • 62. Working with MongoDB ● NoSQL ● Document-oriented stoarage ● Keep data in BSON format ● http://www.mongodb.org/ ● Module => see in npmjs.org ( a lot !!!! ) ○ "redis": "0.8.4" http://en.wikipedia.org/wiki/BSON
  • 63. Start MongoDB server $mongod.exe --dbpath /some/data/path
  • 64. Demo :: Connect to MongoDB var mongo = require('mongodb'); var Server = mongo.Server, var server = new Server( 'localhost', 27017, {auto_reconnect: true} ); db = new Db('persons', server);
  • 65. Demo :: Connect to MongoDB db.open(function(err, db) { if(!err) { db.collection('persons', {strict:true}, function(err, collection) { if (err) { populateDB(); } }); }
  • 66. Demo :: Retrieve all data exports.all = function(req, res){ db.collection('persons', function(err, collection) { collection.find().toArray(function(err, persons) { res.send(persons); }); }); };
  • 67. Demo :: Retrieve data by id exports.one = function(req, res){ var personId = req.params.id; db.collection('persons', function(err, collection) { collection.findOne( {'_id':new BSON.ObjectID(personId)}, function(err, person) { res.send(person); }); }); };
  • 68. Demo :: Create new data exports.insert = function(req, res){ db.collection('persons', function(err, collection) { collection.insert( person, {safe:true}, function(err, result) { }); }); });
  • 69. Demo :: Update data exports.insert = function(req, res){ db.collection('persons', function(err, collection) { collection.update( { '_id':new BSON.ObjectID( personId )}, updatePerson, {safe:true}, function(err, result) { }); }); });
  • 70. Demo :: Delete data by id exports.insert = function(req, res){ db.collection('persons', function(err, collection) { collection.remove( { '_id':new BSON.ObjectID( personId )}, {safe:true}, function(err, result) { }); }); });
  • 71. Design Document ● Collection = persons ● Document structure ○ name ○ gender
  • 72. Working with Redis ● NoSQL ● Key-value data store ● http://redis.io ● Module => see in npmjs.org ( a lot !!!! ) ○ "redis": "0.8.4"
  • 73. Install Redis ● Download from http://redis.io/ ● For Windows OS ○ https://github.com/dmajkic/redis/downloads
  • 74. Start Redis server $redis-server Let’s fun with Redis $redis-cli
  • 75. Design Key-Value ● Key = person_list ○ type = List ○ value = id ● Key = id ○ type = Hash ■ id = <id> ■ name = <name> ■ gender = <gender>
  • 76. Demo :: Connect to Redis var redis = require('redis'); var connection = redis.createClient( { host: 'localhost', port: '6379' } );
  • 77. Favorite Modules ● express ● underscore ● request ● async ● mysql ● Find more in npmjs.org
  • 78. Another project like Node.js ● Vert.x => Polygot programming ● Akka => Scala and Java ● Tornado => Python ● Libevent => C ● EventMachine => Ruby
  • 79. Book
  • 80. Resources ● Sourcecode for demo https://github. com/up1/demo_nodejs ● https://npmjs.org ● http://nodejs.org/ ● http://callbackhell.com/ ● http://nodeframework.com/
  • 81. Q/A