-
Notifications
You must be signed in to change notification settings - Fork 254
/
Copy pathindex.html
executable file
·1453 lines (1082 loc) · 42.7 KB
/
index.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Node.js - 最新Web技术栈</title>
<meta name="description" content="A framework for easily creating beautiful presentations using HTML">
<meta name="author" content="Hakim El Hattab">
<meta name="apple-mobile-web-app-capable" content="yes" />
<meta name="apple-mobile-web-app-status-bar-style" content="black-translucent" />
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no, minimal-ui">
<link rel="stylesheet" href="css/reveal.css">
<link rel="stylesheet" href="css/theme/black.css" id="theme">
<!-- Code syntax highlighting -->
<link rel="stylesheet" href="lib/css/zenburn.css">
<!-- Printing and PDF exports -->
<script>
var link = document.createElement( 'link' );
link.rel = 'stylesheet';
link.type = 'text/css';
link.href = window.location.search.match( /print-pdf/gi ) ? 'css/print/pdf.css' : 'css/print/paper.css';
document.getElementsByTagName( 'head' )[0].appendChild( link );
</script>
<!--[if lt IE 9]>
<script src="lib/js/html5shiv.js"></script>
<![endif]-->
</head>
<body>
<div class="reveal">
<!-- Any section element inside of this container is displayed as a slide -->
<div class="slides">
<section>
<h1>Node && js = 全栈</h1>
<p>高可用架构专用</p>
<p>
<small>Created by <a href="https://cnodejs.org/user/i5ting">i5ting</a> / <a href="http://github.com/i5ting">@i5ting</a></small>
</p>
</section>
<section>
<section data-background="#dddddd">
<h2>Abount Me</h2>
<p>
i5ting 一个开源爱好者
</p>
<a href="#" class="navigate-down">
<img width="600" height="338" data-src="images/me.png" alt="Down arrow">
</a>
</section>
<section data-background="#dddddd">
<h2>Node全栈公众号</h2>
<p>
<p>什么是全栈?一直站在前面讲么?</p>
<br>
<img src='images/nodeonly-wechat.png'/>
</p>
<aside class="notes">
Oh hey, these are some notes. They'll be hidden in your presentation, but you can see them if you open the speaker notes window (hit 's' on your keyboard).
</aside>
</section>
</section>
<section>
<section data-markdown>
## 主要内容
1. Why Node.js ?
1. 我眼中的Node.js核心
1. 快速开发实践
1. 全栈 or 全烂 ?
1. 未来
</section>
<section data-markdown>
## 推荐技术栈
- express 4.x (express最新版本,初学者先别去碰koa)
- mongoose(mongodb)
- bluebird(Promise/A+实现)
- jade(视图层模板)
- mocha(测试)
- node-inspector(调试)
https://github.com/i5ting/express-starter
</section>
</section>
<section data-transition="slide" data-background="#4d7e65" data-background-transition="zoom">
<section data-transition="slide" data-background="#4d7e65" data-background-transition="zoom">
<h2>Part 1:Why Node.js ?</h2>
<p>
以前?现在?
</p>
<pre><code>已经7岁的Node.js,你还熟悉么?</code></pre>
</section>
<section data-markdown>
## 以前我们总是喜欢拿异步说事儿
- event-driven
- non-blocking I/O
结果,今天。。。各种【异步模型】烂大街了
</section>
<section data-markdown>
## 今天,我们拿什么吹牛呢?
```
Node.js' package ecosystem, npm, is the largest ecosystem
of open source libraries in the world.
```
</section>
<section data-markdown>
## 为什么我们选择Node.js ?
即使不优化,性能比其他语言好
即使优化,也比其他语言简单
</section>
<section data-markdown>
## 我们的瓶颈在哪里 ?
- 人(天津招不到人)
- 开发速度(创业公司,跑。。。)
- 传承(以后也要)
</section>
<section data-markdown>
## http verbs -1
verbs = 动词
http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html
```
app.get('/user:id', function (req, res) {
res.send('Hello World!');
});
app.post('/user/create', function (req, res) {
res.send('Got a POST request');
});
app.put('/user/:id', function (req, res) {
res.send('Got a PUT request at /user');
});
app.delete('/user/:id', function (req, res) {
res.send('Got a DELETE request at /user');
});
```
</section>
<section data-markdown>
## http verbs -2
链式写法?
```
router.route('/')
.get($.list)
.post($.create);
```
all代表什么?
```
router.all('/new', $.new);
```
更多node里的verbs(26个),见 https://github.com/jshttp/methods/blob/master/index.js
</section>
<section data-markdown>
## http status code
- http://www.restapitutorial.com/httpstatuscodes.html
- https://github.com/nodejs/io.js/blob/master/lib/_http_server.js
```
500 : 'Internal Server Error',
403 : 'Forbidden',
404 : 'Not Found',
304 : 'Not Modified',
200 : 'OK',
app.get('/user/:id', function(req, res){
res.status(200).json({
a : 1,
b : 2
});
});
```
</section>
<section data-markdown>
## req取参数的3种方法
expressjs里的请求参数,4.x里只有3种
- req.params
- req.body
- req.query
- 已经废弃的api:req.param
</section>
<section data-markdown>
- req.params
```
app.get('/user/:id', function(req, res){
res.send('user ' + req.params.id);
});
```
俗点:取带冒号的参数
</section>
<section data-markdown>
- req.body
```
var app = require('express')();
var bodyParser = require('body-parser');
app.use(bodyParser.json()); // for parsing application/json
app.use(bodyParser.urlencoded({ extended: true })); // for parsing application/x-www-form-urlencoded
app.post('/', function (req, res) {
console.log(req.body);
res.json(req.body);
})
```
可以肯定的一点是req.body一定是post请求,express里依赖的中间件必须有bodyParser,不然req.body是没有的。
</section>
<section data-markdown>
- req.query
```
// GET /search?q=tobi+ferret
req.query.q
// => "tobi ferret"
// GET /shoes?order=desc&shoe[color]=blue&shoe[type]=converse
req.query.order
// => "desc"
req.query.shoe.color
// => "blue"
req.query.shoe.type
// => "converse"
```
query是querystring
</section>
<section data-markdown>
- req.query不一定是get
```
// POST /search?q=tobi+ferret
{a:1,b:2}
req.query.q
// => "tobi ferret"
```
post里的数据看不到得,需要用req.body取
</section>
<section data-markdown>
- 3种不同类型的post
</section>
<section data-markdown>
- Post with x-www-form-urlencoded
see post.html
```
$.ajaxSetup({
contentType: "application/x-www-form-urlencoded; charset=utf-8"
});
$.post("/users/post", { name: "i5a6", time: "2pm" },
function(data){
console.log(data);
}, "json");
```
in routes/users.js
```
router.post('/post', function(req, res) {
// res.send('respond with a resource');
res.json(req.body);
});
```
</section>
<section data-markdown>
#### Post with form-data 主要目的是为了上传
```
var express = require('express')
var multer = require('multer')
var app = express()
app.use(multer({ dest: './uploads/'}))
```
You can access the fields and files in the request object
```
router.post('/post-form-data', function(req, res) {
console.log(req.body)
console.log(req.files)
});
```
Multer will not process any form which is not multipart/form-data
</section>
<section data-markdown>
- Post with raw
To get the raw body content of a request with Content-Type: "text/plain" into req.rawBody you can do:
```
var express = require('./')
var app = express();
app.use(function(req, res, next){
if (req.is('text/*')) {
req.text = '';
req.setEncoding('utf8');
req.on('data', function(chunk){ req.text += chunk });
req.on('end', next);
} else {
next();
}
});
app.post('/', function(req, res){
res.send('got "' + req.text + '"');
});
app.listen(3000)
```
</section>
<section data-markdown>
## 命令行玩法
```
#! /bin/bash
echo -n "post common"
curl -d "a=1&b=2" http://127.0.0.1:3001/users/post
echo -n 'post formdata'
curl -F 'pic=@"img/post-common.png"' -F 'a=1' -F 'b=2' http://127.0.0.1:3001/users/post/formdata
echo -n 'post raw json'
curl -d "{"a":"1","b":"2","c":{"a":"1","b":"2"}}" http://127.0.0.1:3001/users/post
```
如不清楚,请 `man curl`.
</section>
<section data-markdown>
## supertest用法
https://github.com/expressjs/restful-router/blob/master/test/restful-router.test.js
```
var request = require('supertest');
var app = require('../example/app');
describe('restful-router.test.js', function () {
it('should get /users/new => user.new', function (done) {
request(app)
.get('/users/new')
.expect('GET /users/new => new, query: {}')
.expect(200, done);
});
});
```
</section>
<section data-markdown>
## what is rest?
参考阮一峰的文章http://www.ruanyifeng.com/blog/2011/09/restful.html
```
/**
* Auto generate RESTful url routes.
*
* URL routes:
*
* GET /topics[/] => topic.list()
* GET /topics/new => topic.new()
* GET /topics/:id => topic.show()
* GET /topics/:id/edit => topic.edit()
* POST /topics[/] => topic.create()
* PATCH /topics/:id => topic.update()
* DELETE /topics/:id => topic.destroy()
*
*/
```
</section>
<section data-markdown>
## restful api or res.api?
res.api is an express middleware for render json api , it convention over api format like this :
```
{
data: {
},
status: {
code : x,
msg : 'some message'
}
}
```
- 客户端 API 开发总结 https://cnodejs.org/topic/552b3b9382388cec50cf6d95
- res.api用法说明 https://cnodejs.org/topic/55818a0c395a0c1812f18273
</section>
<section>
<h2>如果还不懂http协议?</h2>
花点时间会用个软件就能学会,有兴趣吗?
<p class="fragment">
推荐Postman
<img width="1000" height="538" data-src="images/postman.png" alt="Down arrow">
</p>
</section>
<section>
<h2>如果还还不懂http协议?</h2>
看书吧
<p class="fragment">推荐1
<a href='http://ccbikai.gitbooks.io/http-book/content/index.html'>《HTTP下午茶》
</a>
</p>
<p class="fragment">推荐2
<a href='http://product.china-pub.com/3769819'>《图解HTTP》
</a>
</p>
</section>
</section>
<section data-transition="slide" data-background="#b5533c" data-background-transition="zoom">
<section data-transition="slide" data-background="#b5533c" data-background-transition="zoom">
<h2>Part 2:我眼中的Node.js核心</h2>
<p>
MEAN
</p>
<li>异步流程控制
<li>cli(scaffold)
<li>web framework
</section>
<section data-markdown>
- mongoose用法
```
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/test');
var Cat = mongoose.model('Cat', { name: String });
var kitty = new Cat({ name: 'Zildjian' });
kitty.save(function (err) {
if (err) // ...
console.log('meow');
});
```
</section>
<section data-markdown>
## crud(增删改查)
- save
- find | findOne
- update
- remove
```
Kitten.find({ name: /^Fluff/ }, callback)
Comment.remove({ title: 'baby born from alien father' }, callback);
MyModel.update({ age: { $gt: 18 } }, { oldEnough: true }, fn);
```
</section>
<section data-markdown>
- 了解分页
常见写法
```
db.users.find().skip(pagesize*(n-1)).limit(pagesize)
```
更好的写法
```
db.usermodels.find({'_id' :{
"$gt" :ObjectId("55940ae59c39572851075bfd")}
}).limit(20).sort({_id:-1})
```
</section>
<section data-markdown>
- 了解关系(1对1,1对多)在mongoose里如何实现
```
UserSchema = new Schema({
...
contacts:[]
});
```
</section>
<section data-markdown>
- 了解关系(1对1,1对多,多对多)在mongoose里如何实现
```
ContactSchema = new Schema({
...
owner: {
type: Schema.ObjectId,
required: true,
index: true
}
});
```
</section>
<section data-markdown>
- 了解populate
```
ContactSchema = new Schema({
...
owner: {
type: Schema.ObjectId,
ref: ‘user’
}
});
ContactSchema.find({}).populate(‘owner’).exec(callback);
```
</section>
<section data-markdown>
- 扩展mongoose模型:statics类方法
```
UserSchema.statics.find_by_openid = function(openid, cb) {
return this.findOne({
openid: openid
}, cb);
};
```
调用
```
User.find_by_openid(openid, cb)
```
</section>
<section data-markdown>
- 扩展mongoose模型:methods对象方法
```
UserSchema.methods.is_exist = function(cb) {
var query;
query = {
username: this.username,
password: this.password
};
return this.model('UserModel').findOne(query, cb);
};
```
调用
```
var user = new User({});
user.is_exist(cb)
```
</section>
<section data-markdown>
- hook.js
- 了解pre和post的差别
```
UserSchema.pre('save', function(next) {
var user = this;
if (!user.isModified('password')) return next();
bcrypt.genSalt(SALT_WORK_FACTOR, function(err, salt) {
if (err) return next(err);
bcrypt.hash(user.password, salt, function (err, hash) {
if (err) return next(err);
user.password = hash;
next();
});
});
});
```
</section>
<section data-markdown>
- 了解virtual属性
```
UserSchema.virtual('is_valid').get(function(){
console.log('phone_number = ' +this.phone_number)
if(this.phone_number == undefined | this.invite_code == undefined){
return false;
}
return this.invite_code.length >= 2 && this.phone_number > 0
});
```
</section>
<section data-markdown>
- 了解mongoose的插件机制
```
// lastMod.js
module.exports = exports = function lastModifiedPlugin (schema, options) {
schema.add({ lastMod: Date })
schema.pre('save', function (next) {
this.lastMod = new Date
next()
})
if (options && options.index) {
schema.path('lastMod').index(options.index)
}
}
```
调用
```
// game-schema.js
var lastMod = require('./lastMod');
var Game = new Schema({ ... });
Game.plugin(lastMod, { index: true });
```
</section>
<section data-markdown>
- 了解索引优化
```
ContactSchema = new Schema({
...
owner: {
type: Schema.ObjectId,
required: true,
index: true
}
});
```
也可以这样的
```
ContactSchema.ensureIndexes(owner);
```
</section>
<section data-markdown>
- 了解explain
```
db.usermodels.find({
'_id' :{
"$gt" :ObjectId("55940ae59c39572851075bfd")
}
}).explain()
关注点
- stage:查询策略
- nReturned:返回的文档行数
- needTime:耗时(毫秒)
- indexBounds:所用的索引
```
</section>
<section data-markdown>
- 了解profile
```
profile级别有三种:
- 0:不开启
- 1:记录慢命令,默认为大于100ms
- 2:记录所有命令
- 3、查询profiling记录
```
开启
db.setProfilingLevel(2, 20)
默认记录在system.profile中
db['system.profile'].find()
</section>
<section data-markdown>
## 了解mongodb的部署
- replset
- shard
```
我写的《 mongodb运维之副本集实践》
https://cnodejs.org/topic/5590adbbebf9c92d17e734de
```
</section>
<section data-markdown>
## mongoosedao
模型
```
var TopModel = mongoose.model('TopModel', TopSchema);
var TopModelDao = new MongooseDao(TopModel);
module.exports = TopModelDao;
```
用法
```
require('./db');
var User = require('./User');
User.create({"username":"sss","password":"password"},function(err, user){
console.log(user);
});
User.delete({"username":"sss"},function(err, user){
console.log(user);
});
```
https://github.com/moajs/mongoosedao
</section>
</section>
<section data-transition="slide" data-background="#9c56b9" data-background-transition="zoom">
<section data-transition="slide" data-background="#9c56b9" data-background-transition="zoom">
<h2>Part 3:快速开发实践</h2>
<p>
A promise is defined as an object that has a function as the value for the property then: then(fulfilledHandler, errorHandler, progressHandler)
</p>
<pre><code style="word-wrap: break-word;">http://promisesaplus.com/</code></pre>
</section>
<section data-markdown>
- mvc还是那个mvc
![](images/mvc.png)
</section>
<section data-markdown>
- 代码结构
![](images/models.png)
</section>
<section data-markdown>
- 了解jquery里的then和$.deferred
```
function successFunc(){ console.log( “success!” ); }
function failureFunc(){ console.log( “failure!” ); }
$.when(
$.ajax( "/main.php" ),
$.ajax( "/modules.php" ),
$.ajax( “/lists.php” )
).then( successFunc, failureFunc );
```
</section>
<section data-markdown>
## 了解的node的异步
- 一切都是异步的
- 同步是奢求,要查Api
![](images/api.png)
</section>
<section data-markdown>
## 了解异步的恶心
> 1. 用户登录 2. 增加用户日志 3. 更新用户登录次数
![](images/cb.png)
</section>
<section data-markdown>
## 如果用promise写呢?
![](images/cb_with_promise.png)
</section>
<section data-markdown>
## 如何实现一个promise库
- 了解的then
```
var promise = {
okCallbacks: [],
koCallbacks: [],
then: function (okCallback, koCallback) {
okCallbacks.push(okCallback);
if (koCallback) {
koCallbacks.push(koCallback);
}
}
}
```
</section>
<section data-markdown>
## 如何实现一个promise库
- 了解的resolve和reject
```
var defer = {
promise: promise,
resolve: function (data) {
this.promise.okCallbacks.forEach(function(callback) {
window.setTimeout(function () {
callback(data)
}, 0);
});
},
reject: function (error) {
this.promise.koCallbacks.forEach(function(callback) {
window.setTimeout(function () {
callback(error)
}, 0);
});
}
};
```
</section>
<section data-markdown>
## 如何实现一个promise库
- 测试代码
```
function test() {
var defer = new Defer();
// an example of an async call
serverCall(function (request) {
if (request.status === 200) {
defer.resolve(request.responseText);
} else {
defer.reject(new Error("Status code was " + request.status));
}
});
return defer.promise;
}
test().then(function (text) {
alert(text);
}, function (error) {
alert(error.message);
});
```
</section>
<section data-markdown>
- 了解异步基本场景,比如waterfall这样的路程使用async如何处理
```
var async = require('async');
async.waterfall([
function(callback) {
callback(null, 'one', 'two');
},
function(arg1, arg2, callback) {
// arg1 now equals 'one' and arg2 now equals 'two'
callback(null, 'three');
},
function(arg1, callback) {
// arg1 now equals 'three'
callback(null, 'done');
}
], function (err, result) {
// result now equals 'done'
});
```
</section>
<section data-markdown>
- 了解q和bluebird用法(如果有angularjs经验,推荐q,其他只推荐bluebird)
</section>
<section data-markdown>
- 了解bluebird的promisifyAll用法
```
//Read more about promisification in the API Reference:
//API.md
var fs = Promise.promisifyAll(require("fs"));
fs.readFileAsync("myfile.json").then(JSON.parse).then(function (json) {
console.log("Successful json");
}).catch(SyntaxError, function (e) {
console.error("file contains invalid json");
}).catch(Promise.OperationalError, function (e) {
console.error("unable to read file, because: ", e.message);