SlideShare a Scribd company logo
@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

More Related Content

PDF
Node.js - async for the rest of us.
PDF
Node.js - A Quick Tour
PDF
Introduction to Nodejs
KEY
Building a real life application in node js
PPTX
introduction to node.js
PDF
Non-blocking I/O, Event loops and node.js
PDF
Node js introduction
PDF
Building servers with Node.js
Node.js - async for the rest of us.
Node.js - A Quick Tour
Introduction to Nodejs
Building a real life application in node js
introduction to node.js
Non-blocking I/O, Event loops and node.js
Node js introduction
Building servers with Node.js

What's hot (20)

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

Viewers also liked (20)

PDF
Практика разрешения судебных споров, связанных с персональными данными
PPT
PROEXPOSURE Photos Religion
PPT
Economics 2 2
PPT
Halálugrás telefonnal
PPT
Presentation1
PDF
PPT
Cliftons Powerpoint
PDF
Эквивалентность бумажных и электронных документов
PPT
Fmc Ver 1.3 June 27 2007
PDF
В достаточной ли мере развивается законодательная и нормативно-правовая база ...
PPT
Stroke Recognition And Treatment
PDF
Законодательство о свободе доступа к государственной информации: последствия ...
PPT
Climate Impacts Ana
PPT
Energetic
PPT
Jered
PDF
Minette's Snowman
PDF
Как оказание государственных услуг сочетается с защитой персональных данных
PPT
О перспективах межведомственного электронного документооборота (МЭДО)
PDF
Recensioni2.0 a Webdays2008 by Di Tomaso - Blogmeter
PPT
Climate Impacts
Практика разрешения судебных споров, связанных с персональными данными
PROEXPOSURE Photos Religion
Economics 2 2
Halálugrás telefonnal
Presentation1
Cliftons Powerpoint
Эквивалентность бумажных и электронных документов
Fmc Ver 1.3 June 27 2007
В достаточной ли мере развивается законодательная и нормативно-правовая база ...
Stroke Recognition And Treatment
Законодательство о свободе доступа к государственной информации: последствия ...
Climate Impacts Ana
Energetic
Jered
Minette's Snowman
Как оказание государственных услуг сочетается с защитой персональных данных
О перспективах межведомственного электронного документооборота (МЭДО)
Recensioni2.0 a Webdays2008 by Di Tomaso - Blogmeter
Climate Impacts
Ad

Similar to Introduction to Node.js (20)

PDF
Introduction to REST API with Node.js
PDF
Nodejs and WebSockets
PDF
Node.js
PDF
soft-shake.ch - Hands on Node.js
PPTX
NodeJS
PPTX
Scalable network applications, event-driven - Node JS
PDF
Getting started with node JS
ODP
An Overview of Node.js
PPT
nodejs tutorial foor free download from academia
KEY
Practical Use of MongoDB for Node.js
PDF
Introduction to Node.js Platform
PDF
5.node js
KEY
node.js dao
PPTX
Introduction to Node.js
PPTX
Intro to node and mongodb 1
PPTX
Introduction to node.js
PPTX
Node.js: The What, The How and The When
PDF
Event driven programming -- Node.JS
PPTX
Node.js web-based Example :Run a local server in order to start using node.js...
PPTX
Intro to Node
Introduction to REST API with Node.js
Nodejs and WebSockets
Node.js
soft-shake.ch - Hands on Node.js
NodeJS
Scalable network applications, event-driven - Node JS
Getting started with node JS
An Overview of Node.js
nodejs tutorial foor free download from academia
Practical Use of MongoDB for Node.js
Introduction to Node.js Platform
5.node js
node.js dao
Introduction to Node.js
Intro to node and mongodb 1
Introduction to node.js
Node.js: The What, The How and The When
Event driven programming -- Node.JS
Node.js web-based Example :Run a local server in order to start using node.js...
Intro to Node

More from Somkiat Puisungnoen (20)

PDF
Next of Java 2022
PDF
Sck spring-reactive
PDF
Part 2 :: Spring Boot testing
PDF
vTalk#1 Microservices with Spring Boot
PDF
Lesson learned from React native and Flutter
PDF
Angular :: basic tuning performance
PDF
Shared code between projects
PDF
Distributed Tracing
PDF
Manage data of service
PDF
RobotFramework Meetup at Thailand #2
PDF
Visual testing
PDF
Cloud Native App
PDF
Wordpress for Newbie
PDF
Sck Agile in Real World
PDF
Clean you code
PDF
SCK Firestore at CNX
PDF
Unhappiness Developer
PDF
The Beauty of BAD code
PDF
React in the right way
Next of Java 2022
Sck spring-reactive
Part 2 :: Spring Boot testing
vTalk#1 Microservices with Spring Boot
Lesson learned from React native and Flutter
Angular :: basic tuning performance
Shared code between projects
Distributed Tracing
Manage data of service
RobotFramework Meetup at Thailand #2
Visual testing
Cloud Native App
Wordpress for Newbie
Sck Agile in Real World
Clean you code
SCK Firestore at CNX
Unhappiness Developer
The Beauty of BAD code
React in the right way

Recently uploaded (20)

PDF
NewMind AI Weekly Chronicles - August'25 Week I
PDF
GamePlan Trading System Review: Professional Trader's Honest Take
PDF
Smarter Business Operations Powered by IoT Remote Monitoring
PDF
Using Anchore and DefectDojo to Stand Up Your DevSecOps Function
PDF
Test Bank, Solutions for Java How to Program, An Objects-Natural Approach, 12...
PDF
Automating ArcGIS Content Discovery with FME: A Real World Use Case
PDF
REPORT: Heating appliances market in Poland 2024
PDF
DevOps & Developer Experience Summer BBQ
PDF
Google’s NotebookLM Unveils Video Overviews
PDF
madgavkar20181017ppt McKinsey Presentation.pdf
PPTX
Understanding_Digital_Forensics_Presentation.pptx
PDF
This slide provides an overview Technology
PDF
CIFDAQ's Teaching Thursday: Moving Averages Made Simple
PDF
Reimagining Insurance: Connected Data for Confident Decisions.pdf
PPTX
The-Ethical-Hackers-Imperative-Safeguarding-the-Digital-Frontier.pptx
PPTX
breach-and-attack-simulation-cybersecurity-india-chennai-defenderrabbit-2025....
PDF
Enable Enterprise-Ready Security on IBM i Systems.pdf
PDF
Doc9.....................................
PDF
Why Endpoint Security Is Critical in a Remote Work Era?
PDF
Top Generative AI Tools for Patent Drafting in 2025.pdf
NewMind AI Weekly Chronicles - August'25 Week I
GamePlan Trading System Review: Professional Trader's Honest Take
Smarter Business Operations Powered by IoT Remote Monitoring
Using Anchore and DefectDojo to Stand Up Your DevSecOps Function
Test Bank, Solutions for Java How to Program, An Objects-Natural Approach, 12...
Automating ArcGIS Content Discovery with FME: A Real World Use Case
REPORT: Heating appliances market in Poland 2024
DevOps & Developer Experience Summer BBQ
Google’s NotebookLM Unveils Video Overviews
madgavkar20181017ppt McKinsey Presentation.pdf
Understanding_Digital_Forensics_Presentation.pptx
This slide provides an overview Technology
CIFDAQ's Teaching Thursday: Moving Averages Made Simple
Reimagining Insurance: Connected Data for Confident Decisions.pdf
The-Ethical-Hackers-Imperative-Safeguarding-the-Digital-Frontier.pptx
breach-and-attack-simulation-cybersecurity-india-chennai-defenderrabbit-2025....
Enable Enterprise-Ready Security on IBM i Systems.pdf
Doc9.....................................
Why Endpoint Security Is Critical in a Remote Work Era?
Top Generative AI Tools for Patent Drafting in 2025.pdf

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