之前听说过Node.js,只是知道它可以应用于服务器端,但是对很多具体的东西并不了解。今天在QCon上听了袁锋的分享《Node.js脱离了浏览器的Javascript》之后,顿时有了想立刻试一下的冲动。
根据参考文档说明,从源代码编译安装Node.js需要python2.6或者以上,而通过yum install python.x86_64只能得到2.4.3,所以也要通过源码编译安装python。下面是命令:
# wget
http://www.python.org/ftp/python/3.2.2/Python-3.2.2.tgz # tar xzvf Python-3.2.3.tgz
# cd Python-3.2.2
# ./configure
# make
# make test
# make install
# wget
https://nodeload.github.com/joyent/node/tarball/master # mv master node.tar.gz
# tar xzvf node.tar.gz
# cd joyent-node-84d0b1b
# ./configure --prefix=/opt/node/
# make
# make install
# cd /usr/bin
# ln -s /opt/node/bin/node node
# ln -s /opt/node/bin/node-waf node-waf
在上面的内容中,只用简单的几步就完成了安装。虽然看起来安装都是成功的,但是实际如何就要求我们写一个程序来进行验证一下。由于最近也在学习MongoDB,所以就写一个读取MongoDB数据库:计算actionId为772的日志总数。
# npm install mongodb
npm WARN
mongodb@0.9.6-23 package.json: bugs['web'] should probably be bugs['url']
npm WARN
nodeunit@0.5.1 package.json: bugs['web'] should probably be bugs['url']
>
mongodb@0.9.6-23 install /root/develop/node/node_modules/mongodb
> bash ./install.sh
================================================================================
= =
= To install with C++ bson parser do <npm install mongodb --mongodb:native> =
= the parser only works for node 0.4.X or lower =
= =
================================================================================
Not building native library for cygwin
Using GNU make
mongodb@0.9.6-23 ./node_modules/mongodb
var http = require('http');
var mongodb = require('mongodb');
http.createServer(function(req, res){
res.writeHead(200, {'Content-Type': 'text/plain;charset=utf-8'});
mongodb.connect('mongodb://localhost:40202/log', function(err, conn){
conn.collection('log', function(err, coll){
coll.count({'action': 772}, function(err, count){
res.write('The total of action 772 is ' + count + "./n");
res.end();
});
});
});
}).listen(3000, '127.0.0.1');
console.log('Server running at
http://127.0.0.1:3000/');