SWT Tech Sharing: Node.js + Redis
-
Upload
khasathan -
Category
Technology
-
view
113 -
download
1
Transcript of SWT Tech Sharing: Node.js + Redis
Node.js @khasathan
SWT Tech share
23/12/201317/6/2015
Wait ...
+ Redis 17/6/2015
Outline●Introduction to Node.js●Node.js Anatomy 101●Node Package Manager (NPM)●Node.js Control Flow●Developments●Deployments●Let's play with workshop
Example codes: https://github.com/khasathan/learning-node
Warning!
Buffalo gag alert
JavaScript can run on server side?
Introduction to Node.js
What is Node.js?●“Node.js is a platform built on Chrome's
JavaScript runtime for easily building fast, scalable network applications.”
- Nodejs.org
What is Node.js? (2)
Server side JavaScript
So what's IO.js?●Node.js fork●Bring ES6 to Node community●NPM compatible
Why use Node.js?●Non-Blocking I/O●V8 JavaScript engine (like Google Chrome run-
time)●Many modules (> 40,000)●NPM package manager●Use same language as Back-end/Front-end●High concurrent connections
Node.js use for ...●Modern Web application●Real-time application●Event-based application
Modern Web Application
Simple serverhttp = require('http');
http.createServer(function(req, res) {res.writeHead(200, {
'Content-Type': 'text/html; charset=utf-8'});res.write('Simple Node.js Server');res.end();
}).listen(3000, '127.0.0.1');
Simple server (2)
Who use Node.js
Who use Node.js (2)
Express●Web framework for Node.js●MVC●Template●Pretty URL
$npm install express
RESTful web service●$npm install restify
Socket.io●Real-time application●WebSockets
$npm install socket.io
Socket.io (2)● Socket.io transport
● Websocket● Xhr-polling● Jsonp-polling● Flashsocket● htmlfile
Real-Time Application
http://thstream-khasathan.rhcloud.com
Real-Time Application
Entzonet Notification
Event-Based ApplicationMyCat Back-end
Workers pool - Read un-reviewed documents- Create files queue- Watching status files- Distribute tasks to workers
idle
busy
Files queue
idle
Shouldn't be used for...●RDBMS, transaction●Heavy computation/Huge data processing
Blocking vs Non-Blocking●Blocking
Timeline
1
2
3
Blocking vs Non-Blocking●Non-Blocking
Timeline
1
2
3
Async Programming● Do next task without waiting for current task
end
fs = require('fs')
fs.readFile('bigfile.txt', function(err, data) {console.log(data)
})
console.log('Read big file')
Async Programming (2)
$node read-big-file.js
> Read big file> . . . data from big file . . .
Node.js Anatomy 101
Event Loop
console.log('print 1');
compute(data, function(item) {processItem(item);
});
doLargeCompute();
console.log('print 2');
Call stack
Run-time
Event loop
Message queue
DoLargeCompute
Event loop
Node Package Manager (NPM)
NPM●Package manager for JavaScript●Dependencies management
First step with NPM●$npm initname: (learning-node) version: (1.0.0) description: Example code for Node.js tutorialentry point: (index.js) test command: git repository: https://github.com/khasathan/learning-nodekeywords: author: khasathanlicense: (ISC)
●$npm init
Now, we got package.json file
package.json
npm install/uninstall
# install locally$npm install <package_name>
# install globally$npm install -g <package_name>
# uninstall locally$npm uninstall <package_name>
# uninstall globally$npm uninstall -g <package_name>
npm install/uninstall (2)
● “-g” option you may be use “sudo”● Globally installation you can use its like ls, cd, cp, mv etc.
● Locally installation modules are located in node_modules/
--save options
$npm install - -save redis
--save-dev options
$npm install - -save-dev mocha
npm search
$npm search <keyword>
Node.js Control Flow
Node.js Control Flow●Callback●Promise●Event
Callback vs Promise vs Event●Callback is “Function”●Promise is “Object”●Event is “Event”
Callbackfs = require('fs');
fs.readFile('bigfile.txt', function(err, data) {console.log(data);
});
console.log('print this');
Callback (2)fs = require('fs');
var readfile = function (err, data) {console.log(data);
}
fs.readFile('bigfile.txt', readfile);
console.log('print this');
Callback (3)
fs = require('fs');
var readfile = funtion (err, data) {if(err) throw err;
console.log(data);}
fs.readFile('bigfile.txt', readfile);
console.log('print this');
●How does callback work?
Callback (4)
fs = require('fs');
var readfile = funtion (err, data) {Cb1(function (data1) {
Cb2(function (data2) {Cb3(function (data3) {
Cb4(function (data4) {... do something ...
});});
});});
};
fs.readFile('bigfile.txt', readfile);console.log('print this first');
●Callback pyramid hell
Promise●Delay? Future?●Object that holds value
Promise (2)Fulfilled
The action relating to the promise succeeded.
RejectedThe action relating to the promise failed.
PendingHasn't fulfilled or rejected yet.
SettledHas Fulfilled or rejected.
Promise
See weather-reporter-promise.js
Event● Do function when event fired
Event (2)var mytask = doMyTask();
mytask.on('success', function() {// do this if success
});
mytask.on('progress', function() {// do this if in progress
});
mytask.on('error', function() {// my task if error
});
Callback vs Promise vs Event●Callback is “Function”●Promise is “Object”●Event is “Event”
When we use callback?When we use promise?
When we use event?
Control Flow Libraries●Async●Step●Q●EventEmitter built-in←
Developments
Developments●Make your own function with callback●Custom module●Code quality●Unit testing●Logging●Node Version Manager (NVM)
Make Function with Callback
See function-with-callback.js
Custom module
See folder custom_module/
Code Quality$npm install -g jslint
$jslint file.js
Unit testing●Make small unit works●Unit testing frameworks
●Nodeunit●Mocha●Chai
●TDD/BDD
Node Version Manager (NVM)
●Use several version of Node, IOjs on one machine
●Website https://github.com/creationix/nvm
Deployments
Deployments●Reverse Proxy – use app on port 80●Forever – running app forever
Reverse Proxy●Nginx - Supported (>= V1.3)●HAProxy - Supported●Apache2 (>=V2.4 with websocket tunnel
module)●For Apache < 2.4 you may be use transport
such as xhr-polling, jsonp-polling
Forever●Process monitoring for Node.js●Keep application always running
$sudo npm -g forever$forever list$forever [start|stop] app.js$forever --help
Let's play with workshop
Redis●Redis Stands for “REmote Dictionary Server”●Key-value NoSQL database●PUBLISH/SUBSCRIBE provided
Publish/Subscribe●Sometime we know as “Pub/Sub”●Message-oriented middleware system
Channelsubscriber subscriber
subscriber
publisher
subscribersubscriber
The Funny Scoreboard
https://github.com/khasathan/learning-node