在上一篇文章《在CentOS5.6上安装Node.js》中,只用简单的几步就完成了安装。虽然看起来安装都是成功的,但是实际如何就要求我们写一个程序来进行验证一下。由于最近也在学习MongoDB,所以就写一个读取MongoDB数据库:计算actionId为772的日志总数。
1. 使用安装mongodb驱动
# npm install mongodb npm WARN [email protected] package.json: bugs['web'] should probably be bugs['url'] npm WARN [email protected] package.json: bugs['web'] should probably be bugs['url'] > [email protected] 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 [email protected] ./node_modules/mongodb
根据提示执行:
# cd node_modules/mongodb # bash ./install.sh
注意:驱动必须安装在项目所在的目录下,并不是安装一次所有项目都可以使用。
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/');
启动服务器:
# node mongo.js在浏览器访问http://127.0.0.1:3000,可以看到如下输出: 现在可以说前面的安装过程是正确,开了个好头。
参考文章:
Getting started with VMWare CloudFoundry, MongoDB and Node.js
Blog rolling with mongoDB, express and Node.js