SlideShare a Scribd company logo
1 of 39
Download to read offline
Node.js Flow Control
MiCloud - Simon
首先,今天
都是程式碼....
● node.js
● text editor
● command line tool
● coffee… (可以清醒一點>.<)
請先準備好你的環境...
● modules?
● callback?
● closure?
● json?
測試一下你對Node.js的認識
Modules
[test.js]
var say = require(./say’);
say.hello(‘simon’)
[say.js]
exports.hello = function(word) {
console.log( ‘Hello ’ + word);
}
Callback
[say.js]
exports.hello = function(word, fn) {
fn(‘Hello ’ + word);
}
[test.js]
var say = require(./say’);
say.hello(‘simon’, function(word){
console.log(word);
})
Closure
[say.js]
var f = function(x,y){
return x + y;
}
function foo(callback) {
var a = 1; var b = 2; callback(a,b);
}
foo(f);
JSON
[test.js]
var a = {name:’simon’};
a.sex = ‘man’;
a.say = function(word) {
console.log(‘Hello’ + word);
}
console.log(a.name);
a.say(a.name);
delete a.sex;
大綱
● Write a function with callback
● 基本的流程控制作法
○ array queue流程控制
○ process.nextTick() + callee
● 流程控制套件介紹
○ step
○ q
○ node-promise
● Web流程控制
○ expressjs
Write a function with callback
var request = require('request')
, util = require('util');
var url_ds = 'http://odf.micloud.tw/odf/datasets';
var url_field = 'http://odf.micloud.tw/odf/%s/field';
request.get(url_ds, function(err, res, body){
if(err) console.log(err);
var data = JSON.parse(body);
for(var i = 0 ; i < data.length ; i++){
var ds = data[i];
var url = util.format(url_field, ds);
request.get(url, function(e,r,b){
if(e) console.log(e);
console.log('Dataset: %s', ds);
console.log(b);
});
}
});
沒有做好流程控制,你會
有更多Callback...
基本的流程控制作法
插播一下:for 與 .forEach的差別
var arr = [0,1,2,3,4,5,6,7,8,9];
arr.forEach(function(v){
if(v == 3) return;
console.log(v);
})
var arr = [0,1,2,3,4,5,6,7,8,9];
for(var i = 0; i< arr.length ; i++){
var v = arr[i];
if(v == 3) return;
console.log(v);
}
結果是:0,1,2 結果是:0,1,2,4,5,6,7,8,9
var request = require('request');
var queue =
[ 'http://www.google.com', 'http://micloud.tw/ch/', 'http://tw.yahoo.com'];
queue.forEach(function(v){
var t0 = new Date().getTime();
request({
url: v,
method: 'GET'
}, function(e,r,d) {
var t1 = new Date().getTime();
if(e) console.log(e);
console.log('[%s][%s]%s', v, t1-t0, d.substring(0,50));
});
});
Case - 網路爬蟲範例
reqeust會在瞬間併發,有
可能會被server當做是攻
擊...
var request = require('request');
var queue = ['http://www.google.com','http://micloud.tw','http://tw.yahoo.com'];
function main(){
var t0 = new Date().getTime();
var _this = queue.pop();
request({url: _this,method: 'GET'}, function(e, r, d){
if(e) console.log(e);
var t1 = new Date().getTime();
console.log('[%s][%s]%s', _this, t1-t0, d.substring(0,50));
if(queue.length > 0) {
main();
}
});
}
main();
解法(1):自己Call自己的Loop
如果queue還有值,才會
call下一個request...
插播一下:callee/caller
解法(2):process.nextTick + callee
var request = require('request');
var queue = ['http://www.google.com','http://micloud.tw','http://tw.yahoo.com'];
process.nextTick(function fn1(){
var url = queue.pop();
console.log('Processing %s...', url);
var _callee = arguments.callee;
request.get(url, function(e,r,d){
if(e) console.log(e);
console.log('[%s] word count: %s', url, d.length);
if(queue.length > 0)
process.nextTick(_callee);
});
});
如果queue還有值,才會
call下一個request...
因為Scope的關係,callee
需要先指定給另一個變
數,後面才能取用...
3’rd party modules
Step, q, node-promise
● Github: http://github.com/creationix/step.git
Step模組
Step的用法
var Step = require('step');
Step(
function step1() {
console.log('Step1...');
throw 'error..'; //這個會掉到step2的arguments[0]
return 123; //有return才會往下走
},
function step2() {
console.log('Step2...');
console.log(arguments); //可以觀察接到的參數
return 223;
},
function step3() {
console.log('Step3...');
console.log(arguments);
}
);
var request = require('request');
var queue = ['http://www.google.com',
'http://micloud.tw','http://tw.yahoo.com'];
var Step = require('step');
Step(
function step1() {
console.log('Step1...');
getUrl(queue[0], this);
},
function step2() {
console.log('Step2...');
getUrl(queue[1], this);
},
function step3() {
console.log('Step3...');
getUrl(queue[2], this);
}
);
使用Step操作爬蟲
function getUrl(url, callback) {
//console.log('Processing url:%s...', url);
request.get(url, function(e,r,d){
if(e) console.log(e);
console.log('[%s] word count:%s', url, d.length);
callback(e,d.length);
})
}
其他功能 - parallel()
Step(
// Loads two files in parallel
function loadStuff() {
fs.readFile(__filename, this.parallel());
fs.readFile("/etc/passwd", this.parallel());
},
// Show the result when done
function showStuff(err, code, users) {
if (err) throw err;
console.log(code);
console.log(users);
}
)
其他功能 - group()
Step(
function readDir() { fs.readdir(__dirname, this); },
function readFiles(err, results) {
if (err) throw err;
var group = this.group(); // Create a new group
results.forEach(function (filename) {
fs.readFile(__dirname + "/" + filename, 'utf8', group());
});
},
function showAll(err , files) {
if (err) throw err;
console.dir(files);
}
);
Step注意事項
● Step的操作是擷取callback作為下一個
function的input
● 如果沒有callback的step,必須要return
● 中間step(ex: step2)若沒有return,則程式有可
能會卡住不動(ex: web app)
● 每個step function中的return不代表中斷整個
流程
CommonJS - Promises/A
■ Q Works in both NodeJS and browsers,
compatible with jQuery, thenable, and
usable as remote objects via message
passing
■ RSVP.js A lightweight library that provides
tools for organizing asynchronous code
■ when.js Compact promises with joining
and chaining
■ node-promise Promises for NodeJS
■ jQuery 1.5 is said to be 'based on the
CommonJS Promises/A design'.
■ ForbesLindesay/promises-a A bare bones
implementation of Promises/A intended to
pass https://github.com/domenic/promise-
tests while being as small as possible
■ WinJS / Windows 8 / Metro
q模組
● Github: https://github.com/kriskowal/q
● 範例: https://github.com/kriskowal/q/wiki/Examples-Gallery
安裝q模組
npm install q --save
q提供的功能
● Q.delay
● Q.defer
● Q.nfcall
● Q.nfapply
● Q.ninvoke
● Q.npost
● ...
var Q = require('q')
, request = require('request')
, queue = ['http://www.google.com','http://micloud.tw','http://tw.yahoo.com'];
var fn = function(url) {
var deferred = Q.defer();
request.get(url, function(e,r,d){
console.log('[%s] word count:%s', url, d.length);
deferred.resolve();
});
return deferred.promise;
};
Q.allResolved( [ fn(queue[0]), fn(queue[1]), fn(queue[2]) ] )
.then(function(){
console.log(‘end...’)
}).done();
使用q操做爬蟲
q只
保
證
開
始
順
序
延續剛剛的範例
…(skip)
var out = function (x, y, z) {
var d = Q.defer();
console.log('x:%s, y:%s, z:%s', x, y, z);
d.resolve();
return d.promise;
};
Q.allResolved([fn(queue[0]), fn(queue[1]), fn(queue[2])])
.spread(out)
.then(function(){
console.log('end...');
})
.done();
使用spread來接收執
行結果值
node-promise模組
● Github: https://github.com/kriszyp/node-promise
安裝node-promise模組
npm install node-promise --save
var Promise = require("node-promise").Promise
, request = require('request');
var p = new Promise();
function step1(){
request.get("http://www.google.com", function(e,r,d){
console.log('>>1');
p.resolve(d);
});
}
step1();
p.then(function(d){
console.log('>>2');
console.log('word count:%s', d.length);
},
function(err){
console.log(err);
}
)
使用node-promise操做爬蟲
可以透過then來取回
resolve的回傳值
var Promise = require("node-promise").Promise
, request = require('request')
var queue = ["http://www.google.com", "http://micloud.tw", "http://tw.yahoo.com"];
var p;
function step1(url){
p = new Promise();
request({
url : url,
method : "GET"
},
function(e,r,d){
console.log('>>url:%s', url);
p.resolve(d);
});
}
step1(queue[0]);
step1(queue[1]);
錯誤的操作範例
因為promise(p)的scope問
題,會導致runtime
exception
var Promise = require("node-promise").Promise
, request = require('request')
, util = require('util')
var site = ‘http://odf.micloud.tw’
var url = site + '/odf/datasets'
var url_detail = site + '/odf/%s/field';
function step1(url){
var p = new Promise();
request({
url : url,
method : "GET"
},
function(e,r,d){
p.resolve(JSON.parse(d));
});
return p;
}
延續剛剛的範例
step1(url)
.then(function(d){
for(var i = 0 ; i< d.length ; i++){
step1(util.format(url_detail, d[i]))
.then(function(d){
console.log(d);
});
}
})
使用return promise的方式,串連then操作
使用function scope限制promise存續區域
Web Flow Control
expressjs
ExpressJS中的流程控制
● next()
透過流程控制增加authfilter
//增加req.headers.auth認證
function authfilter(req, res, next){
if(req.headers.auth == 'demo')
next(); //next代表通過此filter
else
//認證錯誤,則回傳statusCode與錯誤訊息
res.send(401, 'Auth Error!');
}
//則在routing中可以安插在真正執行route之前
app.get('/users', authfilter, user.list);
Reference
● http://opennodes.arecord.us
● http://calculist.org/blog/2011/12/14/why-
coroutines-wont-work-on-the-web/
● http://wiki.commonjs.org/wiki/Promises/A
● https://github.com/basicallydan/q-
examples/blob/master/wait-for-multiple-
promises.js
● https://github.com/kriskowal/q/wiki/API-
Reference
End...

More Related Content

What's hot

Mysql handle socket
Mysql handle socketMysql handle socket
Mysql handle socketPhilip Zhong
 
Compare mysql5.1.50 mysql5.5.8
Compare mysql5.1.50 mysql5.5.8Compare mysql5.1.50 mysql5.5.8
Compare mysql5.1.50 mysql5.5.8Philip Zhong
 
Call stack, event loop and async programming
Call stack, event loop and async programmingCall stack, event loop and async programming
Call stack, event loop and async programmingMasters Academy
 
Protocol handler in Gecko
Protocol handler in GeckoProtocol handler in Gecko
Protocol handler in GeckoChih-Hsuan Kuo
 
Google App Engine Developer - Day3
Google App Engine Developer - Day3Google App Engine Developer - Day3
Google App Engine Developer - Day3Simon Su
 
Node.js/io.js Native C++ Addons
Node.js/io.js Native C++ AddonsNode.js/io.js Native C++ Addons
Node.js/io.js Native C++ AddonsChris Barber
 
The Ring programming language version 1.10 book - Part 94 of 212
The Ring programming language version 1.10 book - Part 94 of 212The Ring programming language version 1.10 book - Part 94 of 212
The Ring programming language version 1.10 book - Part 94 of 212Mahmoud Samir Fayed
 
RxJS - 封裝程式的藝術
RxJS - 封裝程式的藝術RxJS - 封裝程式的藝術
RxJS - 封裝程式的藝術名辰 洪
 
JavaSE7 Launch Event: Java7xGroovy
JavaSE7 Launch Event: Java7xGroovyJavaSE7 Launch Event: Java7xGroovy
JavaSE7 Launch Event: Java7xGroovyYasuharu Nakano
 
Writing native bindings to node.js in C++
Writing native bindings to node.js in C++Writing native bindings to node.js in C++
Writing native bindings to node.js in C++nsm.nikhil
 
JJUG CCC 2011 Spring
JJUG CCC 2011 SpringJJUG CCC 2011 Spring
JJUG CCC 2011 SpringKiyotaka Oku
 
201913001 khairunnisa progres_harian
201913001 khairunnisa progres_harian201913001 khairunnisa progres_harian
201913001 khairunnisa progres_harianKhairunnisaPekanbaru
 
Everything you wanted to know about Stack Traces and Heap Dumps
Everything you wanted to know about Stack Traces and Heap DumpsEverything you wanted to know about Stack Traces and Heap Dumps
Everything you wanted to know about Stack Traces and Heap DumpsAndrei Pangin
 
Effective Modern C++ - Item 35 & 36
Effective Modern C++ - Item 35 & 36Effective Modern C++ - Item 35 & 36
Effective Modern C++ - Item 35 & 36Chih-Hsuan Kuo
 
Wprowadzenie do technologi Big Data i Apache Hadoop
Wprowadzenie do technologi Big Data i Apache HadoopWprowadzenie do technologi Big Data i Apache Hadoop
Wprowadzenie do technologi Big Data i Apache HadoopSages
 
TDC2018SP | Trilha Go - Processando analise genetica em background com Go
TDC2018SP | Trilha Go - Processando analise genetica em background com GoTDC2018SP | Trilha Go - Processando analise genetica em background com Go
TDC2018SP | Trilha Go - Processando analise genetica em background com Gotdc-globalcode
 
생산적인 개발을 위한 지속적인 테스트
생산적인 개발을 위한 지속적인 테스트생산적인 개발을 위한 지속적인 테스트
생산적인 개발을 위한 지속적인 테스트기룡 남
 

What's hot (20)

Mysql handle socket
Mysql handle socketMysql handle socket
Mysql handle socket
 
Compare mysql5.1.50 mysql5.5.8
Compare mysql5.1.50 mysql5.5.8Compare mysql5.1.50 mysql5.5.8
Compare mysql5.1.50 mysql5.5.8
 
Call stack, event loop and async programming
Call stack, event loop and async programmingCall stack, event loop and async programming
Call stack, event loop and async programming
 
Protocol handler in Gecko
Protocol handler in GeckoProtocol handler in Gecko
Protocol handler in Gecko
 
Google App Engine Developer - Day3
Google App Engine Developer - Day3Google App Engine Developer - Day3
Google App Engine Developer - Day3
 
Node.js/io.js Native C++ Addons
Node.js/io.js Native C++ AddonsNode.js/io.js Native C++ Addons
Node.js/io.js Native C++ Addons
 
The Ring programming language version 1.10 book - Part 94 of 212
The Ring programming language version 1.10 book - Part 94 of 212The Ring programming language version 1.10 book - Part 94 of 212
The Ring programming language version 1.10 book - Part 94 of 212
 
RxJS - 封裝程式的藝術
RxJS - 封裝程式的藝術RxJS - 封裝程式的藝術
RxJS - 封裝程式的藝術
 
JavaSE7 Launch Event: Java7xGroovy
JavaSE7 Launch Event: Java7xGroovyJavaSE7 Launch Event: Java7xGroovy
JavaSE7 Launch Event: Java7xGroovy
 
Writing native bindings to node.js in C++
Writing native bindings to node.js in C++Writing native bindings to node.js in C++
Writing native bindings to node.js in C++
 
Learning Dtrace
Learning DtraceLearning Dtrace
Learning Dtrace
 
Tugas 2
Tugas 2Tugas 2
Tugas 2
 
JJUG CCC 2011 Spring
JJUG CCC 2011 SpringJJUG CCC 2011 Spring
JJUG CCC 2011 Spring
 
201913001 khairunnisa progres_harian
201913001 khairunnisa progres_harian201913001 khairunnisa progres_harian
201913001 khairunnisa progres_harian
 
Fia fabila
Fia fabilaFia fabila
Fia fabila
 
Everything you wanted to know about Stack Traces and Heap Dumps
Everything you wanted to know about Stack Traces and Heap DumpsEverything you wanted to know about Stack Traces and Heap Dumps
Everything you wanted to know about Stack Traces and Heap Dumps
 
Effective Modern C++ - Item 35 & 36
Effective Modern C++ - Item 35 & 36Effective Modern C++ - Item 35 & 36
Effective Modern C++ - Item 35 & 36
 
Wprowadzenie do technologi Big Data i Apache Hadoop
Wprowadzenie do technologi Big Data i Apache HadoopWprowadzenie do technologi Big Data i Apache Hadoop
Wprowadzenie do technologi Big Data i Apache Hadoop
 
TDC2018SP | Trilha Go - Processando analise genetica em background com Go
TDC2018SP | Trilha Go - Processando analise genetica em background com GoTDC2018SP | Trilha Go - Processando analise genetica em background com Go
TDC2018SP | Trilha Go - Processando analise genetica em background com Go
 
생산적인 개발을 위한 지속적인 테스트
생산적인 개발을 위한 지속적인 테스트생산적인 개발을 위한 지속적인 테스트
생산적인 개발을 위한 지속적인 테스트
 

Viewers also liked

เฉลยการวัดตำแหน่งและกระจาย
เฉลยการวัดตำแหน่งและกระจายเฉลยการวัดตำแหน่งและกระจาย
เฉลยการวัดตำแหน่งและกระจายkrurutsamee
 
Algor genetico
Algor geneticoAlgor genetico
Algor geneticotiojoffre
 
Yo soy asihugo_chavez
Yo soy asihugo_chavezYo soy asihugo_chavez
Yo soy asihugo_chavezjochefer
 
Inscripción por internet 2011
Inscripción por internet 2011Inscripción por internet 2011
Inscripción por internet 2011caarl23
 
Roteiro para Cadastro de Usuário no Blog AFT
Roteiro para Cadastro de Usuário no Blog AFTRoteiro para Cadastro de Usuário no Blog AFT
Roteiro para Cadastro de Usuário no Blog AFTPaloma Chaves
 
Jorge leonardo rivera lozano
Jorge leonardo rivera lozanoJorge leonardo rivera lozano
Jorge leonardo rivera lozanoJorge Rivera
 
Vygostsky teorias sobre el aprendizaje.
Vygostsky teorias sobre el aprendizaje.Vygostsky teorias sobre el aprendizaje.
Vygostsky teorias sobre el aprendizaje.rociogiraldo
 
Atividade 3.4 - Executando uma Atividade
Atividade 3.4 - Executando uma AtividadeAtividade 3.4 - Executando uma Atividade
Atividade 3.4 - Executando uma AtividadeMarcos Antonnnio
 
Rough guide to data vault modelling
Rough guide to data vault modellingRough guide to data vault modelling
Rough guide to data vault modellingDmitri Apassov
 
Catàleg Aki Setembre- Ofertes Parc d'Aro
Catàleg Aki Setembre- Ofertes Parc d'AroCatàleg Aki Setembre- Ofertes Parc d'Aro
Catàleg Aki Setembre- Ofertes Parc d'AroParc d'Aro
 

Viewers also liked (20)

เฉลยการวัดตำแหน่งและกระจาย
เฉลยการวัดตำแหน่งและกระจายเฉลยการวัดตำแหน่งและกระจาย
เฉลยการวัดตำแหน่งและกระจาย
 
Brayanpalomino
BrayanpalominoBrayanpalomino
Brayanpalomino
 
Orm android
Orm androidOrm android
Orm android
 
Algor genetico
Algor geneticoAlgor genetico
Algor genetico
 
Yo soy asihugo_chavez
Yo soy asihugo_chavezYo soy asihugo_chavez
Yo soy asihugo_chavez
 
Inscripción por internet 2011
Inscripción por internet 2011Inscripción por internet 2011
Inscripción por internet 2011
 
Roteiro para Cadastro de Usuário no Blog AFT
Roteiro para Cadastro de Usuário no Blog AFTRoteiro para Cadastro de Usuário no Blog AFT
Roteiro para Cadastro de Usuário no Blog AFT
 
Jorge leonardo rivera lozano
Jorge leonardo rivera lozanoJorge leonardo rivera lozano
Jorge leonardo rivera lozano
 
Vygostsky teorias sobre el aprendizaje.
Vygostsky teorias sobre el aprendizaje.Vygostsky teorias sobre el aprendizaje.
Vygostsky teorias sobre el aprendizaje.
 
Animales 2
Animales 2Animales 2
Animales 2
 
ComunidadMujer
ComunidadMujerComunidadMujer
ComunidadMujer
 
Atividade 3.4 - Executando uma Atividade
Atividade 3.4 - Executando uma AtividadeAtividade 3.4 - Executando uma Atividade
Atividade 3.4 - Executando uma Atividade
 
JAZUG 3周年LT
JAZUG 3周年LTJAZUG 3周年LT
JAZUG 3周年LT
 
3 hipertrofia
3 hipertrofia3 hipertrofia
3 hipertrofia
 
Resume-Fall 2016
Resume-Fall 2016Resume-Fall 2016
Resume-Fall 2016
 
Recurso nuevo
Recurso nuevoRecurso nuevo
Recurso nuevo
 
Rough guide to data vault modelling
Rough guide to data vault modellingRough guide to data vault modelling
Rough guide to data vault modelling
 
Actividad 2
Actividad 2Actividad 2
Actividad 2
 
Catàleg Aki Setembre- Ofertes Parc d'Aro
Catàleg Aki Setembre- Ofertes Parc d'AroCatàleg Aki Setembre- Ofertes Parc d'Aro
Catàleg Aki Setembre- Ofertes Parc d'Aro
 
Presentacion 1y2
Presentacion 1y2Presentacion 1y2
Presentacion 1y2
 

Similar to Node.js flow control

Openstack taskflow 簡介
Openstack taskflow 簡介Openstack taskflow 簡介
Openstack taskflow 簡介kao kuo-tung
 
Promise: async programming hero
Promise: async programming heroPromise: async programming hero
Promise: async programming heroThe Software House
 
Real World Lessons on the Pain Points of Node.js Applications
Real World Lessons on the Pain Points of Node.js ApplicationsReal World Lessons on the Pain Points of Node.js Applications
Real World Lessons on the Pain Points of Node.js ApplicationsBen Hall
 
Node.js System: The Landing
Node.js System: The LandingNode.js System: The Landing
Node.js System: The LandingHaci Murat Yaman
 
Groovy On Trading Desk (2010)
Groovy On Trading Desk (2010)Groovy On Trading Desk (2010)
Groovy On Trading Desk (2010)Jonathan Felch
 
Matthew Eernisse, NodeJs, .toster {webdev}
Matthew Eernisse, NodeJs, .toster {webdev}Matthew Eernisse, NodeJs, .toster {webdev}
Matthew Eernisse, NodeJs, .toster {webdev}.toster
 
Node.js Event Loop & EventEmitter
Node.js Event Loop & EventEmitterNode.js Event Loop & EventEmitter
Node.js Event Loop & EventEmitterSimen Li
 
Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter...
Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter...Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter...
Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter...Domenic Denicola
 
ModemFrontEndops
ModemFrontEndopsModemFrontEndops
ModemFrontEndopsmicrobean
 
Ten useful JavaScript tips & best practices
Ten useful JavaScript tips & best practicesTen useful JavaScript tips & best practices
Ten useful JavaScript tips & best practicesAnkit Rastogi
 
Future Decoded - Node.js per sviluppatori .NET
Future Decoded - Node.js per sviluppatori .NETFuture Decoded - Node.js per sviluppatori .NET
Future Decoded - Node.js per sviluppatori .NETGianluca Carucci
 
The why and how of moving to php 5.4/5.5
The why and how of moving to php 5.4/5.5The why and how of moving to php 5.4/5.5
The why and how of moving to php 5.4/5.5Wim Godden
 
How to Write Node.js Module
How to Write Node.js ModuleHow to Write Node.js Module
How to Write Node.js ModuleFred Chien
 
Playing With Fire - An Introduction to Node.js
Playing With Fire - An Introduction to Node.jsPlaying With Fire - An Introduction to Node.js
Playing With Fire - An Introduction to Node.jsMike Hagedorn
 
Workshop 1: Good practices in JavaScript
Workshop 1: Good practices in JavaScriptWorkshop 1: Good practices in JavaScript
Workshop 1: Good practices in JavaScriptVisual Engineering
 

Similar to Node.js flow control (20)

Performance patterns
Performance patternsPerformance patterns
Performance patterns
 
Openstack taskflow 簡介
Openstack taskflow 簡介Openstack taskflow 簡介
Openstack taskflow 簡介
 
Promise: async programming hero
Promise: async programming heroPromise: async programming hero
Promise: async programming hero
 
Real World Lessons on the Pain Points of Node.js Applications
Real World Lessons on the Pain Points of Node.js ApplicationsReal World Lessons on the Pain Points of Node.js Applications
Real World Lessons on the Pain Points of Node.js Applications
 
Node.js System: The Landing
Node.js System: The LandingNode.js System: The Landing
Node.js System: The Landing
 
Groovy On Trading Desk (2010)
Groovy On Trading Desk (2010)Groovy On Trading Desk (2010)
Groovy On Trading Desk (2010)
 
Matthew Eernisse, NodeJs, .toster {webdev}
Matthew Eernisse, NodeJs, .toster {webdev}Matthew Eernisse, NodeJs, .toster {webdev}
Matthew Eernisse, NodeJs, .toster {webdev}
 
Sane Async Patterns
Sane Async PatternsSane Async Patterns
Sane Async Patterns
 
Node.js Event Loop & EventEmitter
Node.js Event Loop & EventEmitterNode.js Event Loop & EventEmitter
Node.js Event Loop & EventEmitter
 
Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter...
Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter...Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter...
Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter...
 
Nodejs - A quick tour (v6)
Nodejs - A quick tour (v6)Nodejs - A quick tour (v6)
Nodejs - A quick tour (v6)
 
ModemFrontEndops
ModemFrontEndopsModemFrontEndops
ModemFrontEndops
 
Ten useful JavaScript tips & best practices
Ten useful JavaScript tips & best practicesTen useful JavaScript tips & best practices
Ten useful JavaScript tips & best practices
 
Future Decoded - Node.js per sviluppatori .NET
Future Decoded - Node.js per sviluppatori .NETFuture Decoded - Node.js per sviluppatori .NET
Future Decoded - Node.js per sviluppatori .NET
 
The why and how of moving to php 5.4/5.5
The why and how of moving to php 5.4/5.5The why and how of moving to php 5.4/5.5
The why and how of moving to php 5.4/5.5
 
How to Write Node.js Module
How to Write Node.js ModuleHow to Write Node.js Module
How to Write Node.js Module
 
Playing With Fire - An Introduction to Node.js
Playing With Fire - An Introduction to Node.jsPlaying With Fire - An Introduction to Node.js
Playing With Fire - An Introduction to Node.js
 
NodeJS for Beginner
NodeJS for BeginnerNodeJS for Beginner
NodeJS for Beginner
 
Workshop 1: Good practices in JavaScript
Workshop 1: Good practices in JavaScriptWorkshop 1: Good practices in JavaScript
Workshop 1: Good practices in JavaScript
 
NodeJS
NodeJSNodeJS
NodeJS
 

More from Simon Su

Kubernetes Basic Operation
Kubernetes Basic OperationKubernetes Basic Operation
Kubernetes Basic OperationSimon Su
 
Google IoT Core 初體驗
Google IoT Core 初體驗Google IoT Core 初體驗
Google IoT Core 初體驗Simon Su
 
JSDC 2017 - 使用google cloud 從雲到端,動手刻個IoT
JSDC 2017 - 使用google cloud 從雲到端,動手刻個IoTJSDC 2017 - 使用google cloud 從雲到端,動手刻個IoT
JSDC 2017 - 使用google cloud 從雲到端,動手刻個IoTSimon Su
 
GCPUG.TW meetup #28 - GKE上運作您的k8s服務
GCPUG.TW meetup #28 - GKE上運作您的k8s服務GCPUG.TW meetup #28 - GKE上運作您的k8s服務
GCPUG.TW meetup #28 - GKE上運作您的k8s服務Simon Su
 
Google Cloud Platform Special Training
Google Cloud Platform Special TrainingGoogle Cloud Platform Special Training
Google Cloud Platform Special TrainingSimon Su
 
GCE Windows Serial Console Usage Guide
GCE Windows Serial Console Usage GuideGCE Windows Serial Console Usage Guide
GCE Windows Serial Console Usage GuideSimon Su
 
GCPNext17' Extend 開始GCP了嗎?
GCPNext17' Extend   開始GCP了嗎?GCPNext17' Extend   開始GCP了嗎?
GCPNext17' Extend 開始GCP了嗎?Simon Su
 
Try Cloud Spanner
Try Cloud SpannerTry Cloud Spanner
Try Cloud SpannerSimon Su
 
Google Cloud Monitoring
Google Cloud MonitoringGoogle Cloud Monitoring
Google Cloud MonitoringSimon Su
 
Google Cloud Computing compares GCE, GAE and GKE
Google Cloud Computing compares GCE, GAE and GKEGoogle Cloud Computing compares GCE, GAE and GKE
Google Cloud Computing compares GCE, GAE and GKESimon Su
 
JCConf 2016 - Google Dataflow 小試
JCConf 2016 - Google Dataflow 小試JCConf 2016 - Google Dataflow 小試
JCConf 2016 - Google Dataflow 小試Simon Su
 
JCConf 2016 - Dataflow Workshop Labs
JCConf 2016 - Dataflow Workshop LabsJCConf 2016 - Dataflow Workshop Labs
JCConf 2016 - Dataflow Workshop LabsSimon Su
 
JCConf2016 - Dataflow Workshop Setup
JCConf2016 - Dataflow Workshop SetupJCConf2016 - Dataflow Workshop Setup
JCConf2016 - Dataflow Workshop SetupSimon Su
 
GCPUG meetup 201610 - Dataflow Introduction
GCPUG meetup 201610 - Dataflow IntroductionGCPUG meetup 201610 - Dataflow Introduction
GCPUG meetup 201610 - Dataflow IntroductionSimon Su
 
Brocade - Stingray Application Firewall
Brocade - Stingray Application FirewallBrocade - Stingray Application Firewall
Brocade - Stingray Application FirewallSimon Su
 
使用 Raspberry pi + fluentd + gcp cloud logging, big query 做iot 資料搜集與分析
使用 Raspberry pi + fluentd + gcp cloud logging, big query 做iot 資料搜集與分析使用 Raspberry pi + fluentd + gcp cloud logging, big query 做iot 資料搜集與分析
使用 Raspberry pi + fluentd + gcp cloud logging, big query 做iot 資料搜集與分析Simon Su
 
Docker in Action
Docker in ActionDocker in Action
Docker in ActionSimon Su
 
Google I/O 2016 Recap - Google Cloud Platform News Update
Google I/O 2016 Recap - Google Cloud Platform News UpdateGoogle I/O 2016 Recap - Google Cloud Platform News Update
Google I/O 2016 Recap - Google Cloud Platform News UpdateSimon Su
 
IThome DevOps Summit - IoT、docker與DevOps
IThome DevOps Summit - IoT、docker與DevOpsIThome DevOps Summit - IoT、docker與DevOps
IThome DevOps Summit - IoT、docker與DevOpsSimon Su
 
Google Cloud Platform Introduction - 2016Q3
Google Cloud Platform Introduction - 2016Q3Google Cloud Platform Introduction - 2016Q3
Google Cloud Platform Introduction - 2016Q3Simon Su
 

More from Simon Su (20)

Kubernetes Basic Operation
Kubernetes Basic OperationKubernetes Basic Operation
Kubernetes Basic Operation
 
Google IoT Core 初體驗
Google IoT Core 初體驗Google IoT Core 初體驗
Google IoT Core 初體驗
 
JSDC 2017 - 使用google cloud 從雲到端,動手刻個IoT
JSDC 2017 - 使用google cloud 從雲到端,動手刻個IoTJSDC 2017 - 使用google cloud 從雲到端,動手刻個IoT
JSDC 2017 - 使用google cloud 從雲到端,動手刻個IoT
 
GCPUG.TW meetup #28 - GKE上運作您的k8s服務
GCPUG.TW meetup #28 - GKE上運作您的k8s服務GCPUG.TW meetup #28 - GKE上運作您的k8s服務
GCPUG.TW meetup #28 - GKE上運作您的k8s服務
 
Google Cloud Platform Special Training
Google Cloud Platform Special TrainingGoogle Cloud Platform Special Training
Google Cloud Platform Special Training
 
GCE Windows Serial Console Usage Guide
GCE Windows Serial Console Usage GuideGCE Windows Serial Console Usage Guide
GCE Windows Serial Console Usage Guide
 
GCPNext17' Extend 開始GCP了嗎?
GCPNext17' Extend   開始GCP了嗎?GCPNext17' Extend   開始GCP了嗎?
GCPNext17' Extend 開始GCP了嗎?
 
Try Cloud Spanner
Try Cloud SpannerTry Cloud Spanner
Try Cloud Spanner
 
Google Cloud Monitoring
Google Cloud MonitoringGoogle Cloud Monitoring
Google Cloud Monitoring
 
Google Cloud Computing compares GCE, GAE and GKE
Google Cloud Computing compares GCE, GAE and GKEGoogle Cloud Computing compares GCE, GAE and GKE
Google Cloud Computing compares GCE, GAE and GKE
 
JCConf 2016 - Google Dataflow 小試
JCConf 2016 - Google Dataflow 小試JCConf 2016 - Google Dataflow 小試
JCConf 2016 - Google Dataflow 小試
 
JCConf 2016 - Dataflow Workshop Labs
JCConf 2016 - Dataflow Workshop LabsJCConf 2016 - Dataflow Workshop Labs
JCConf 2016 - Dataflow Workshop Labs
 
JCConf2016 - Dataflow Workshop Setup
JCConf2016 - Dataflow Workshop SetupJCConf2016 - Dataflow Workshop Setup
JCConf2016 - Dataflow Workshop Setup
 
GCPUG meetup 201610 - Dataflow Introduction
GCPUG meetup 201610 - Dataflow IntroductionGCPUG meetup 201610 - Dataflow Introduction
GCPUG meetup 201610 - Dataflow Introduction
 
Brocade - Stingray Application Firewall
Brocade - Stingray Application FirewallBrocade - Stingray Application Firewall
Brocade - Stingray Application Firewall
 
使用 Raspberry pi + fluentd + gcp cloud logging, big query 做iot 資料搜集與分析
使用 Raspberry pi + fluentd + gcp cloud logging, big query 做iot 資料搜集與分析使用 Raspberry pi + fluentd + gcp cloud logging, big query 做iot 資料搜集與分析
使用 Raspberry pi + fluentd + gcp cloud logging, big query 做iot 資料搜集與分析
 
Docker in Action
Docker in ActionDocker in Action
Docker in Action
 
Google I/O 2016 Recap - Google Cloud Platform News Update
Google I/O 2016 Recap - Google Cloud Platform News UpdateGoogle I/O 2016 Recap - Google Cloud Platform News Update
Google I/O 2016 Recap - Google Cloud Platform News Update
 
IThome DevOps Summit - IoT、docker與DevOps
IThome DevOps Summit - IoT、docker與DevOpsIThome DevOps Summit - IoT、docker與DevOps
IThome DevOps Summit - IoT、docker與DevOps
 
Google Cloud Platform Introduction - 2016Q3
Google Cloud Platform Introduction - 2016Q3Google Cloud Platform Introduction - 2016Q3
Google Cloud Platform Introduction - 2016Q3
 

Recently uploaded

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
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 3652toLead Limited
 
Powerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time ClashPowerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time Clashcharlottematthew16
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Mark Simos
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationSlibray Presentation
 
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Wonjun Hwang
 
Story boards and shot lists for my a level piece
Story boards and shot lists for my a level pieceStory boards and shot lists for my a level piece
Story boards and shot lists for my a level piececharlottematthew16
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsRizwan Syed
 
"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
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brandgvaughan
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
APIForce Zurich 5 April Automation LPDG
APIForce Zurich 5 April  Automation LPDGAPIForce Zurich 5 April  Automation LPDG
APIForce Zurich 5 April Automation LPDGMarianaLemus7
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupFlorian Wilhelm
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Enterprise Knowledge
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxhariprasad279825
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsMark Billinghurst
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsMemoori
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 3652toLead Limited
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLScyllaDB
 

Recently uploaded (20)

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?
 
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptxE-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
 
Powerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time ClashPowerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time Clash
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck Presentation
 
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
 
Story boards and shot lists for my a level piece
Story boards and shot lists for my a level pieceStory boards and shot lists for my a level piece
Story boards and shot lists for my a level piece
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL Certs
 
"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
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brand
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
APIForce Zurich 5 April Automation LPDG
APIForce Zurich 5 April  Automation LPDGAPIForce Zurich 5 April  Automation LPDG
APIForce Zurich 5 April Automation LPDG
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project Setup
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptx
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR Systems
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial Buildings
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQL
 

Node.js flow control

  • 3. ● node.js ● text editor ● command line tool ● coffee… (可以清醒一點>.<) 請先準備好你的環境...
  • 4. ● modules? ● callback? ● closure? ● json? 測試一下你對Node.js的認識
  • 5. Modules [test.js] var say = require(./say’); say.hello(‘simon’) [say.js] exports.hello = function(word) { console.log( ‘Hello ’ + word); }
  • 6. Callback [say.js] exports.hello = function(word, fn) { fn(‘Hello ’ + word); } [test.js] var say = require(./say’); say.hello(‘simon’, function(word){ console.log(word); })
  • 7. Closure [say.js] var f = function(x,y){ return x + y; } function foo(callback) { var a = 1; var b = 2; callback(a,b); } foo(f);
  • 8. JSON [test.js] var a = {name:’simon’}; a.sex = ‘man’; a.say = function(word) { console.log(‘Hello’ + word); } console.log(a.name); a.say(a.name); delete a.sex;
  • 9. 大綱 ● Write a function with callback ● 基本的流程控制作法 ○ array queue流程控制 ○ process.nextTick() + callee ● 流程控制套件介紹 ○ step ○ q ○ node-promise ● Web流程控制 ○ expressjs
  • 10. Write a function with callback var request = require('request') , util = require('util'); var url_ds = 'http://odf.micloud.tw/odf/datasets'; var url_field = 'http://odf.micloud.tw/odf/%s/field'; request.get(url_ds, function(err, res, body){ if(err) console.log(err); var data = JSON.parse(body); for(var i = 0 ; i < data.length ; i++){ var ds = data[i]; var url = util.format(url_field, ds); request.get(url, function(e,r,b){ if(e) console.log(e); console.log('Dataset: %s', ds); console.log(b); }); } }); 沒有做好流程控制,你會 有更多Callback...
  • 12. 插播一下:for 與 .forEach的差別 var arr = [0,1,2,3,4,5,6,7,8,9]; arr.forEach(function(v){ if(v == 3) return; console.log(v); }) var arr = [0,1,2,3,4,5,6,7,8,9]; for(var i = 0; i< arr.length ; i++){ var v = arr[i]; if(v == 3) return; console.log(v); } 結果是:0,1,2 結果是:0,1,2,4,5,6,7,8,9
  • 13. var request = require('request'); var queue = [ 'http://www.google.com', 'http://micloud.tw/ch/', 'http://tw.yahoo.com']; queue.forEach(function(v){ var t0 = new Date().getTime(); request({ url: v, method: 'GET' }, function(e,r,d) { var t1 = new Date().getTime(); if(e) console.log(e); console.log('[%s][%s]%s', v, t1-t0, d.substring(0,50)); }); }); Case - 網路爬蟲範例 reqeust會在瞬間併發,有 可能會被server當做是攻 擊...
  • 14. var request = require('request'); var queue = ['http://www.google.com','http://micloud.tw','http://tw.yahoo.com']; function main(){ var t0 = new Date().getTime(); var _this = queue.pop(); request({url: _this,method: 'GET'}, function(e, r, d){ if(e) console.log(e); var t1 = new Date().getTime(); console.log('[%s][%s]%s', _this, t1-t0, d.substring(0,50)); if(queue.length > 0) { main(); } }); } main(); 解法(1):自己Call自己的Loop 如果queue還有值,才會 call下一個request...
  • 16. 解法(2):process.nextTick + callee var request = require('request'); var queue = ['http://www.google.com','http://micloud.tw','http://tw.yahoo.com']; process.nextTick(function fn1(){ var url = queue.pop(); console.log('Processing %s...', url); var _callee = arguments.callee; request.get(url, function(e,r,d){ if(e) console.log(e); console.log('[%s] word count: %s', url, d.length); if(queue.length > 0) process.nextTick(_callee); }); }); 如果queue還有值,才會 call下一個request... 因為Scope的關係,callee 需要先指定給另一個變 數,後面才能取用...
  • 17. 3’rd party modules Step, q, node-promise
  • 19. Step的用法 var Step = require('step'); Step( function step1() { console.log('Step1...'); throw 'error..'; //這個會掉到step2的arguments[0] return 123; //有return才會往下走 }, function step2() { console.log('Step2...'); console.log(arguments); //可以觀察接到的參數 return 223; }, function step3() { console.log('Step3...'); console.log(arguments); } );
  • 20. var request = require('request'); var queue = ['http://www.google.com', 'http://micloud.tw','http://tw.yahoo.com']; var Step = require('step'); Step( function step1() { console.log('Step1...'); getUrl(queue[0], this); }, function step2() { console.log('Step2...'); getUrl(queue[1], this); }, function step3() { console.log('Step3...'); getUrl(queue[2], this); } ); 使用Step操作爬蟲 function getUrl(url, callback) { //console.log('Processing url:%s...', url); request.get(url, function(e,r,d){ if(e) console.log(e); console.log('[%s] word count:%s', url, d.length); callback(e,d.length); }) }
  • 21. 其他功能 - parallel() Step( // Loads two files in parallel function loadStuff() { fs.readFile(__filename, this.parallel()); fs.readFile("/etc/passwd", this.parallel()); }, // Show the result when done function showStuff(err, code, users) { if (err) throw err; console.log(code); console.log(users); } )
  • 22. 其他功能 - group() Step( function readDir() { fs.readdir(__dirname, this); }, function readFiles(err, results) { if (err) throw err; var group = this.group(); // Create a new group results.forEach(function (filename) { fs.readFile(__dirname + "/" + filename, 'utf8', group()); }); }, function showAll(err , files) { if (err) throw err; console.dir(files); } );
  • 23. Step注意事項 ● Step的操作是擷取callback作為下一個 function的input ● 如果沒有callback的step,必須要return ● 中間step(ex: step2)若沒有return,則程式有可 能會卡住不動(ex: web app) ● 每個step function中的return不代表中斷整個 流程
  • 24. CommonJS - Promises/A ■ Q Works in both NodeJS and browsers, compatible with jQuery, thenable, and usable as remote objects via message passing ■ RSVP.js A lightweight library that provides tools for organizing asynchronous code ■ when.js Compact promises with joining and chaining ■ node-promise Promises for NodeJS ■ jQuery 1.5 is said to be 'based on the CommonJS Promises/A design'. ■ ForbesLindesay/promises-a A bare bones implementation of Promises/A intended to pass https://github.com/domenic/promise- tests while being as small as possible ■ WinJS / Windows 8 / Metro
  • 25. q模組 ● Github: https://github.com/kriskowal/q ● 範例: https://github.com/kriskowal/q/wiki/Examples-Gallery
  • 27. q提供的功能 ● Q.delay ● Q.defer ● Q.nfcall ● Q.nfapply ● Q.ninvoke ● Q.npost ● ...
  • 28. var Q = require('q') , request = require('request') , queue = ['http://www.google.com','http://micloud.tw','http://tw.yahoo.com']; var fn = function(url) { var deferred = Q.defer(); request.get(url, function(e,r,d){ console.log('[%s] word count:%s', url, d.length); deferred.resolve(); }); return deferred.promise; }; Q.allResolved( [ fn(queue[0]), fn(queue[1]), fn(queue[2]) ] ) .then(function(){ console.log(‘end...’) }).done(); 使用q操做爬蟲 q只 保 證 開 始 順 序
  • 29. 延續剛剛的範例 …(skip) var out = function (x, y, z) { var d = Q.defer(); console.log('x:%s, y:%s, z:%s', x, y, z); d.resolve(); return d.promise; }; Q.allResolved([fn(queue[0]), fn(queue[1]), fn(queue[2])]) .spread(out) .then(function(){ console.log('end...'); }) .done(); 使用spread來接收執 行結果值
  • 32. var Promise = require("node-promise").Promise , request = require('request'); var p = new Promise(); function step1(){ request.get("http://www.google.com", function(e,r,d){ console.log('>>1'); p.resolve(d); }); } step1(); p.then(function(d){ console.log('>>2'); console.log('word count:%s', d.length); }, function(err){ console.log(err); } ) 使用node-promise操做爬蟲 可以透過then來取回 resolve的回傳值
  • 33. var Promise = require("node-promise").Promise , request = require('request') var queue = ["http://www.google.com", "http://micloud.tw", "http://tw.yahoo.com"]; var p; function step1(url){ p = new Promise(); request({ url : url, method : "GET" }, function(e,r,d){ console.log('>>url:%s', url); p.resolve(d); }); } step1(queue[0]); step1(queue[1]); 錯誤的操作範例 因為promise(p)的scope問 題,會導致runtime exception
  • 34. var Promise = require("node-promise").Promise , request = require('request') , util = require('util') var site = ‘http://odf.micloud.tw’ var url = site + '/odf/datasets' var url_detail = site + '/odf/%s/field'; function step1(url){ var p = new Promise(); request({ url : url, method : "GET" }, function(e,r,d){ p.resolve(JSON.parse(d)); }); return p; } 延續剛剛的範例 step1(url) .then(function(d){ for(var i = 0 ; i< d.length ; i++){ step1(util.format(url_detail, d[i])) .then(function(d){ console.log(d); }); } }) 使用return promise的方式,串連then操作 使用function scope限制promise存續區域
  • 37. 透過流程控制增加authfilter //增加req.headers.auth認證 function authfilter(req, res, next){ if(req.headers.auth == 'demo') next(); //next代表通過此filter else //認證錯誤,則回傳statusCode與錯誤訊息 res.send(401, 'Auth Error!'); } //則在routing中可以安插在真正執行route之前 app.get('/users', authfilter, user.list);
  • 38. Reference ● http://opennodes.arecord.us ● http://calculist.org/blog/2011/12/14/why- coroutines-wont-work-on-the-web/ ● http://wiki.commonjs.org/wiki/Promises/A ● https://github.com/basicallydan/q- examples/blob/master/wait-for-multiple- promises.js ● https://github.com/kriskowal/q/wiki/API- Reference