zzzhc's Blog

stay curious

Nodejs

nodejs Evented I/O for V8 JavaScript.

node的目标是提供一种简单的方式来构建可伸缩的网络程序。在node里几乎没有函数会直接执行IO操作,进程从不会阻塞在某个IO等待上。event, callback是node中两个主要的概念,因为IO操作不阻塞,通过event, callback来实现是很自然的。

这一两年node发展很快,有了包管理器(npm),也出现了各种各样的module, 如

有了这些之后要用javascript开发一个web app相对容易多了。

这两天简单试了下,用express, hamljs, node-mongodb-native写了一个最简单的blog app.

安装环境 * install node

1
2
3
4
5
#download source code from http://nodejs.org/dist/
$ wget http://nodejs.org/dist/node-v0.4.5.tar.gz
$ tar -xf node-v0.4.5.tar.gz
$ cd node-v0.4.5
$ ./configure && make && sudo make install
  • install mongodb
1
2
3
4
5
6
7
#http://www.mongodb.org/downloads
$ wget http://fastdl.mongodb.org/linux/mongodb-linux-i686-1.8.1.tgz
$ tar -xf mongodb-linux-i686-1.8.1.tgz
$ cd mongodb-linux-i686-1.8.1
$ sudo mkdir -p /data/db
$ sudo chown `id -u` -R /data
$ bin/mongod # start mongodb server
  • install npm
1
2
3
$ git clone http://github.com/isaacs/npm.git
$ cd npm
$ sudo make install
  • install modules
1
2
3
$ sudo npm install express
$ sudo npm install hamljs
$ sudo npm install mongodb

express指南见http://expressjs.com/guide.html,它的route方式跟rails比算很弱的,没有对restful的直接支持,但在加上methodOverride后都可以自己定义出来。 模板引擎用hamljs, 通过app.register(‘.haml’, require(‘hamljs’))指定。在hamljs layout里要嵌入其它模板内容时可以用!= body。partial可以用!= partial(“post.haml”, posts)。!=的意思是对后面的内容不作escape, 细节可以看hamljs代码,很短,不到700行。 mongodb client用起来比较费劲,一层一层的callback, 适当封装下应该会好使点。 最终的代码放在https://github.com/nodepress/draft 性能看起来还是很好的,production模式下(NODE_ENV=production node blog.js) 并发5个连接(ab -c 5 -n 1000 http://localhost:3000/posts/)的结果 Time per request: 1.145 [ms] (mean, across all concurrent requests)

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
$ ab -c 5 -n 1000 http://localhost:3000/posts/
....
Server Software:
Server Hostname:        localhost
Server Port:            3000

Document Path:          /posts/
Document Length:        2950 bytes

Concurrency Level:      5
Time taken for tests:   1.145 seconds
Complete requests:      1000
Failed requests:        0
Write errors:           0
Total transferred:      3073000 bytes
HTML transferred:       2950000 bytes
Requests per second:    873.02 [#/sec] (mean)
Time per request:       5.727 [ms] (mean)
Time per request:       1.145 [ms] (mean, across all concurrent requests)
Transfer rate:          2619.90 [Kbytes/sec] received

Connection Times (ms)
              min  mean[+/-sd] median   max
Connect:        0    0   0.0      0       0
Processing:     3    6   1.8      5      22
Waiting:        3    6   1.8      5      22
Total:          3    6   1.8      5      22

Percentage of the requests served within a certain time (ms)
  50%      5
  66%      5
  75%      6
  80%      6
  90%      7
  95%      8
  98%     14
  99%     16
  100%     22 (longest request)

Comments